执行直到满足循环条件 - 但循环继续 - Powershell

Do Until Loop Condition Met - but Loop continues - Powershell

您好,我在 powershell 中遇到一个问题,Do Until Condition 为真,但循环没有停止。如果我将 -eq 更改为 0。它将停止...基本上这应该做的是获取文本文件中的计算机数量。将该数字存储在 $count 中。然后为列表中的每台计算机重新启动服务,直到到达最后一台。

$computers = gc C:\temp\computers.txt
$count = $computers.count
Do {
   foreach($computer in $computers){
        $readCount = $computer.ReadCount
        gwmi win32_service -ComputerName $computer | where {$_.name -like "*was*"} | Restart-Service
   } 
}
Until (($count - $readCount) -eq 1)

这里不需要 Do-Until 循环,因为您可以遍历计算机。要跳过最后一台计算机,请使用带有 -SkipLast 1 参数的 Select-Object cmdlet:

Get-Content 'C:\temp\computers.txt' | Select-Object -SkipLast 1 | Forach-Object {
    gwmi win32_service -ComputerName $computer | 
        where {$_.name -like "*was*"} | 
        Restart-Service
}