#PSTip Wait for a Service to reach a specified status

So, in your script, you need to wait for a service until it reaches a specified status and performs an action based on the new state. One way to achieve this, and an ineffective one, would be to poll the status using a while loop:

$svc = Get-Service W3SVC
while($svc.State -ne 'Stopped')
{
	Start-Sleep -Seconds 1
}

... do your thing here...

Instead, you could wait for the service to reach the specified status using one of its native methods:

$svc.WaitForStatus('Stopped')

This will wait infinitely for the service to reach the specified state, and script execution is halted until the service state changes. Waiting forever for the service to change its state may not be what we want to do, so instead we can use the second overload of the WaitForStatus method and specify an expiration time-out value.

# wait for 5 seconds
$svc.WaitForStatus('Stopped','00:00:05')

... the rest of the script ...

About the author: Shay Levy

Shay Levy is a Co-founder and editor of the PowerShell Magazine. He is a multiple-year recipient of the Microsoft MVP award, and a Microsoft Certified Trainer (MCT). Shay often covers PowerShell related topics on his blog and you can also follow him on Twitter at @ShayLevy

Related Posts

%d bloggers like this: