【问题标题】:PowerShell - Add counter to while loopPowerShell - 将计数器添加到 while 循环
【发布时间】:2016-11-23 21:49:00
【问题描述】:

我想知道是否有人可以帮助我解决这个问题。我有这个声明来停止服务,但有时服务有时不会由于依赖关系而停止,所以我添加了一个 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-hostrn "Service not stopped."

感谢任何帮助。谢谢大家。

【问题讨论】:

标签: powershell


【解决方案1】:

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

【讨论】:

  • 这正是我所需要的。非常感谢!
猜你喜欢
  • 2018-03-16
  • 2017-06-21
  • 2021-09-18
  • 2021-12-22
  • 2016-04-02
  • 1970-01-01
  • 1970-01-01
  • 2022-08-09
  • 2020-08-24
相关资源
最近更新 更多