PowerShell - 向while循环添加计数器

Mik*_*ike 4 powershell

我想知道是否有人可以帮我解决这个问题.我有这个声明来停止服务,但有时服务有时不会因依赖性而停止,所以我添加了一个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 
}
Run Code Online (Sandbox Code Playgroud)

我想添加一个计数器来在60秒后停止循环,如果服务仍然在运行,那么到write-hostrn "Service not stopped."

任何帮助表示赞赏.谢谢大家.

Tes*_*ler 5

60/5 = 12个循环.

while (test -and ($counter++ -lt 12)) {
    #stop-service 
    #start-sleep
}
Run Code Online (Sandbox Code Playgroud)

但经过长时间的测试,它可能更具可读性:

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))
Run Code Online (Sandbox Code Playgroud)