PowerShell - add counter to while loop

I was wondering if anyone could help me with this. I have this statement to stop the service, but sometimes the service sometimes does not stop due to dependencies, so I added 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 write-hostrn "Service not stopped."

Any help is appreciated. Thanks to everyone.

+4
source share
1 answer

60/5 = 12 loops.

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

But with this long test, it may be more readable:

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))
+5
source

Source: https://habr.com/ru/post/1648530/


All Articles