4

I was wondering if anyone could help me out with this. I have this statement to stop a service but at times the service sometimes doesn't stop due to dependencies so i added a start-sleep -s 5.

while($module | Get-Service | ? {$_.Status -eq "Running" -or $_.Status -eq "Stopping"}) 
{
   set-service $module -ComputerName $targetserver -StartupType Disabled -Status Stopped -PassThru
        ;
  Start-Sleep -Seconds 5 #keep repeating stop services every 5 seconds until all services have stopped 
}

I want to add a counter to stop the loop after 60 seconds and if the service is still running then to write-hostrn "Service not stopped."

Any help is appreciated. Thanks all.

Mike
  • 133
  • 2
  • 4
  • 13
  • 1
    Time to pull out your [stop watch (or other similar built-in functionality)](http://stackoverflow.com/questions/3513650/timing-a-commands-execution-in-powershell) – gravity Jul 20 '16 at 15:45

1 Answers1

5

60/5 = 12 loops.

while (test -and ($counter++ -lt 12)) {
    #stop-service 
    #start-sleep
}

But with that long test, it might be more readable as:

do 
{ 
    set-service $module -ComputerName $targetserver -StartupType Disabled -Status Stopped -PassThru
    Start-Sleep -Seconds 5

    $status = ($module | Get-Service).Status
    $loopCounter++

} while ($status -in ('Running', 'Stopping') -and ($loopCounter -lt 12))
TessellatingHeckler
  • 27,511
  • 4
  • 48
  • 87