Waiting for Service State

by Aug 2, 2013

Most high-level cmdlets dealing with services have built-in code to wait for state changes. So when you run Restart-Service to restart a service, the cmdlet will pause the script until the service indeed has restarted, and even display a warning message if this takes some time.

If you'd like to write your own service management logic, you may be better off using the low-level methods provided by service objects. This way, you can stop a service and do other things while the service is stopping, or deal with dependent services.

Here's how you would access the Spooler service and use its low-level methods to stop it and then wait 2 seconds maximum for the state change to occur:

$service = Get-Service -Name Spooler
$service.Stop()
$service.WaitForStatus('Stopped','00:00:02')
if ($service.Status -ne 'Stopped') 
  { Write-Warning 'Something is fishy here...' }
$service 

In this case, if state change did not occur within the 2 seconds timeout, a warning is output. You could, of course, do smarter things instead. Note that to change service status, you probably need Administrator privileges. Note also that low-level methods like Start() and Stop() raise errors when the service is not in the proper status to start or stop it.

Twitter This Tip! ReTweet this Tip!