PowerShell to Restart SharePoint Farm Windows Services

Introduction

One of the steps that I suggest when deploying upgrades to SharePoint solutions is before you do a Solution upgrade restart all the SharePoint related services.

So in a SharePoint 2010 Farm that would be:-

  • SharePoint Administration Service
  • SharePoint Timer Service
  • World Wide Web Publishing Service
  • IIS Admin Service
  • Web Analytics Service
    The reason is that certain processes (i.e. SharePoint Timer Service) can lock assemblies and cause solution deployment to fail.

However this step is a pain in the ass when you have a more than one server!

To help ease the pain here is a PowerShell script which will loop through all the servers on the farm (ignore the database servers) and restart the appropriate services.

The great thing about this script is it will also ensure that services that are required to be running are also running such as the SharePoint Administration Service!

The Script

param
(
	[Parameter(Mandatory=$false, HelpMessage='-ServiceNames Optional, provide a set of service names to restart.')]
	[Array]$ServiceNames=@("SharePoint 2010 Timer","SharePoint 2010 Administration","IIS Admin Service","World Wide Web Publishing Service")
);

Write-Host "Attempting to get SharePoint Servers in Farm" -ForegroundColor White;
$farm = Get-SPFarm;
$servers = $farm.Servers;
Write-Host "Found" $servers.Count "Servers in Farm (including database servers)" -ForegroundColor White;
foreach($server in $servers)
{
	if($server.Role -ne [Microsoft.SharePoint.Administration.SPServerRole]::Invalid)
	{
		Write-Host "Attempting to restart services on" $server.Name -ForegroundColor White;
		foreach($serviceName in $ServiceNames)
		{
			$serviceInstance = Get-Service -ComputerName $server.Name -Name $serviceName -ErrorAction SilentlyContinue;
			if($serviceInstance -ne $null)
			{
				Write-Host "Attempting to restart service" $serviceName ".." -ForegroundColor White -NoNewline;
				try
				{
					$restartServiceOutput="";
					Restart-Service -InputObject $serviceInstance;
					Write-Host " Done!" -ForegroundColor Green;
				}
				catch
				{
					Write-Host "Error Occured: " $_.Message;
				}
			}
		}
	}
}

Notice you can extend the Services that are restarted by adding/removing service names to the array parameter $ServiceNames.

Hope that helps.

One Comment

Thoughts? Comments about this post? Please leave them here..

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.