0

I have a PowerShell script where I am stopping a Windows service. I, then, wish to wait until the service shows a 'Stopped' status. I issue the appropriate command to stop the service. I have tried to use a WHILE loop similar to...

While ((Get-Service -Name $ServiceName).Status -ne 'Stopped')
{
     Start-Sleep -s 5
}

I have also added a counter to the above WHILE loop that checks the counter to see that it is not over a count of 5. The counter works as it exits the WHILE loop but the service still does not show a status of 'Stopped'. The service must be stopped before I continue with the remaining code in the script.

Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37
JamesM
  • 1
  • 1
  • But are you running `Stop-Service` or `.Stop()` for the service you're trying to stop prior to the code you're showing us and the process still shows as `'Running'`? Do you get any errors? – Santiago Squarzon Aug 04 '21 at 16:38
  • Is the service stopping and just slow, or does the service fail to stop? Why are you breaking out of the loop if the service must be stopped before moving on? Maybe change to `While (($Service = Get-Service -name $ServiceName).Status -ne 'Stopped')` then inside the loop `If($Service.Status -eq 'Running'){ Stop-Service -Name $ServiceName -Force}` – TheMadTechnician Aug 04 '21 at 16:56
  • 2
    To be clear, `Stop-Service` **already** waits for the service to go down before continuing, unless you specify `-NoWait`. The timeout is based on the service itself, but if it needs to be longer, you can override it: https://stackoverflow.com/a/35871759/7411885 – Cpt.Whale Aug 04 '21 at 17:18
  • 1
    If `Stop-Service` errors out though, it won't end the script since the error is non-terminating. This can be changed with `Stop-Service MyService -ErrorAction Stop` – Cpt.Whale Aug 04 '21 at 17:21

1 Answers1

0

Just use WaitForStatus: ServiceController.WaitForStatus Method

Mickey Cohen
  • 997
  • 7
  • 23