Powershell Wait for service to be stopped or started

The following will loop and verify the status of the given services until the number of services with the "Running" state is equal to zero (hence they are stopped), so you can use this if you are waiting for services to Stop.

I've added a $MaxRepeat variable, which will prevent this from running for ever. It will run 20 times max as defined.

$services = "Service Bus *"
$maxRepeat = 20
$status = "Running" # change to Stopped if you want to wait for services to start

do 
{
    $count = (Get-Service $services | ? {$_.status -eq $status}).count
    $maxRepeat--
    sleep -Milliseconds 600
} until ($count -eq 0 -or $maxRepeat -eq 0)

I couldn't get the 'count' strategy, that Micky posted, to work, so here is how i solved it:

I created a function, that takes a searchString (this could be "Service Bus *") and the status that i expect the services should reach.

function WaitUntilServices($searchString, $status)
{
    # Get all services where DisplayName matches $searchString and loop through each of them.
    foreach($service in (Get-Service -DisplayName $searchString))
    {
        # Wait for the service to reach the $status or a maximum of 30 seconds
        $service.WaitForStatus($status, '00:00:30')
    }
}

The function can now be called with

WaitUntilServices "Service Bus *" "Stopped"

or

WaitUntilServices "Service Bus *" "Running"

If the timeout period is reached, a not so graceful exception is thrown:

Exception calling "WaitForStatus" with "2" argument(s): "Time out has expired and the operation has not been completed."

In addition to the answer of mgarde this one liner might be useful if you just want to wait for a single service (also inspired by a post from Shay Levy):

(Get-Service SomeInterestingService).WaitForStatus('Running')

Tags:

Powershell