Gatewarden Gatewarden -4 years ago 371
PowerShell Question

Powershell Wait for service to be stopped or started

I have searched both this forum and through google and can't find what I need.
I have a quite large script and I'm looking for some code that will check if the service is started or stopped before proceeding to the next step.

The function it self need to loop untill it's either stopped or started (Going to have a function for Stopped and one for Started).

In total 4 services which almost have the same name, so Service Bus * can be used as a wildcard.

Answer Source

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

    $count = (Get-Service $services | ? {$_.status -eq $status}).count
    sleep -Milliseconds 600
} until ($count -eq 0 -or $maxRepeat -eq 0)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download