我想知道是否有人可以帮助我解决这个问题。我有这个语句来停止服务,但有时服务有时不会由于依赖关系而停止,所以我添加了一个 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
}
我想添加一个计数器以在 60 秒后停止循环,如果服务仍在运行,则添加到
write-host
r n "Service not stopped."
任何帮助表示赞赏。谢谢大家。
最佳答案
60/5 = 12 个循环。
while (test -and ($counter++ -lt 12)) {
#stop-service
#start-sleep
}
但是通过那个长时间的测试,它可能更具可读性:
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))
关于PowerShell - 向 while 循环添加计数器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38484967/