PoSh Get-Service wait for status

So you’re writing a script and you have to start a service and/or wait for it. You can use Get-Service to retrieve the status but you’ll need to put it in a loop so you can wait for the status you need. You’ll probably end up with something like this:

This is pretty basic. It’ll wait indefinitely until the service has been started. So you continue on your quest to get rock-solid code and you build in a timeout:

So now you’re up to 6 lines of  code just to wait for a service and I’ve even placed some stuff on a single line which I usually spread out over more lines and the script doesn’t have any commenting either. On top of that it’s much more complex then it should be.

In comes the WaitForStatus method

The object you get back from Get-Service has a method called WaitForStatus which you can easily use to wait for a service and include a timeout. So this’ll dramatically clean up your code, especially when using it multiple times and the code is less complex.

One thought on “PoSh Get-Service wait for status

Leave a Reply