PowerShell – Service Restart Status

SPowerShell Service Statusometimes it is necessary to restart multiple services on a Windows machine and PowerShell makes such an operation easy to achieve but what if you need to wait for a specific status before restarting the next service?

The most commonly implemented solution for service restart status is something similar to:

$svc = Get-Service Browser
while($svc.State -ne 'Stopped')
{
   Start-Sleep -Seconds 1
}
 
... do something really cool here...

While this approach does work it is not the most efficient way of achieving our goal, the Get-Service CmdLet has a handy property named Status which ca be used as follows:

$svc = Get-Service Browser

$svc.WaitForStatus('Stopped')

...do something really cool here...

The above code will instruct PowerShell to wait for service to reach the desired status, stopped in our example, you can also specify a timeout value so that PowerShell will wait for a specific amount of time before timing out:

$svc = Get-Service Browser

$svc.WaitForStatus('Stopped','00:00:10')

...do something really cool here...

The above code will instruct PowerShell to wait for 10 seconds before throwing an exception for the service not reaching the desired Status

The full documentation for this method can be found on the MSDN website.

Do you know any other method to check the service restart status with PowerShell? Why don’t you leave me a comment and share with the community?

 

Advertisements

Leave a Reply

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s