Mike
Mike

Reputation: 143

PowerShell - Add counter to while loop

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.

Upvotes: 5

Views: 11020

Answers (1)

TessellatingHeckler
TessellatingHeckler

Reputation: 28963

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))

Upvotes: 7

Related Questions