Powershell Wait for service to be stopped or started

后端 未结 4 845
暗喜
暗喜 2021-01-31 19:36

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 star

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-31 20:27

    I had to tweak this a bit with multiple counters because this service purposely starts and stops slowly. The original script got me on the right track. I had to wait for the service to be in a completely stopped status before I could move on because I'm actually restarting that same service. You could probably remove the "sleep," but I don't mind leaving it in. You could probably remove everything and just use the $stopped variable. :)

        # change to Stopped if you want to wait for services to start
        $running = "Running" 
        $stopPending = "StopPending"
        $stopped = "Stopped"
        do 
        {
            $count1 = (Get-Service $service | ? {$_.status -eq $running}).count
            sleep -Milliseconds 600
            $count2 = (Get-Service $service | ? {$_.status -eq $stopPending}).count
            sleep -Milliseconds 600
            $count3 = (Get-Service $service | ? {$_.status -eq $stopped}).count
            sleep -Milliseconds 600
        } until ($count1 -eq 0 -and $count2 -eq 0 -and $count3 -eq 1)
    

提交回复
热议问题