Tuesday, February 18, 2014

Restart IIS in all servers in a SharePoint 2010 farm


Step 1. Create a folder with 2 powershell blank files as below image.








 
Step 2. Open Sam.Functions.PS1 file and copy the below code snippet.
# Stop specified service on all servers within the farm
function Stop-ServiceOnFarm
{
    param ($ServiceName)
     
    foreach ($server in (Get-SPServer | Where {$_.Role -ne "Invalid"}) )
    {
        $service = Get-WmiObject -computer $server.Name Win32_Service -Filter "Name='$($ServiceName)'"
         
        if ($service -eq $null -or $service.State -eq "Stopped") {
            continue
        }
         
        Write-Host "Stopping '$($ServiceName)' on $($server.Name)..."
        $service.InvokeMethod('StopService',$Null)
         
        do {
            Start-Sleep -s 5
            $service = Get-WmiObject -computer $server.Name Win32_Service -Filter "Name='$($ServiceName)'"   
        } while ($service.State -ne "Stopped")
    }  
}

# Starts specified service on all servers within the farm
function Start-ServiceOnFarm
{
    param ($ServiceName)
     
     foreach ($server in (Get-SPServer | Where {$_.Role -ne "Invalid"}) )
     {
        $service = Get-WmiObject -computer $server.Name Win32_Service -Filter "Name='$($ServiceName)'"
         
        if ($service -eq $null -or $service.State -eq "Started" -or $service.State -eq "Starting") {
            continue
        }
         
        Write-Host "Starting '$($ServiceName)' on $($server.Name)..."
        $service.InvokeMethod('StartService',$Null)
     }
}

# Restarts IIS on all servers within the farm
function Restart-IIS
{
    Stop-ServiceOnFarm "W3SVC"
    Stop-ServiceOnFarm "SMTPSVC"
    Stop-ServiceOnFarm "IISADMIN"
     
   Start-ServiceOnFarm "IISADMIN"
   Start-ServiceOnFarm "SMTPSVC"
   Start-ServiceOnFarm "W3SVC"
}
 

Step 3. Open the file Sam.RestartIISOnFarm and copy the below snippet.
 
  if ($SCRIPT:scriptDir -eq $null -or $SCRIPT:scriptDir -eq "")
{
 $SCRIPT:scriptDir = (Get-Location -PSProvider FileSystem).ProviderPath
}

# ** Load My functions
Write-Host "* Loading Functions..."
. (Join-Path $scriptDir "Sam.Functions.ps1")

Restart-IIS

Step 4. Close and Save the files and call the .\Sam.RestartIISOnFarm.ps1 file from any server in the farm.

No comments:

Post a Comment