Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Wait for service to be stopped or started

Tags:

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.

like image 415
Gatewarden Avatar asked Jan 28 '15 07:01

Gatewarden


People also ask

How do I wait for a service to stop in PowerShell?

The PowerShell cmdlets Stop-Service and Start-Service will wait until the services are fully stopped and started respectively. You can use the -Force switch for Stop-Service to make it also stop services that depend on the service you are trying to stop.

How do I stop and start services in PowerShell?

To start or stop a service through PowerShell, you can use the Start-Service or the Stop Service cmdlet, followed by the name of the service that you want to start or stop. For instance, you might enter Stop-Service DHCP or Start-Service DHCP.

Is there a wait command in PowerShell?

The Wait-Process cmdlet waits for one or more running processes to be stopped before accepting input. In the PowerShell console, this cmdlet suppresses the command prompt until the processes are stopped. You can specify a process by process name or process ID (PID), or pipe a process object to Wait-Process .


2 Answers

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." 
like image 118
mgarde Avatar answered Sep 19 '22 13:09

mgarde


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') 
like image 42
CodeFox Avatar answered Sep 21 '22 13:09

CodeFox