【问题标题】:Do Until Loop Condition Met - but Loop continues - Powershell直到满足循环条件 - 但循环继续 - Powershell
【发布时间】:2016-06-02 15:34:08
【问题描述】:

您好,我在 Powershell 中遇到了一个问题,即执行直到条件为真,但循环不会停止。如果我将 -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)

【问题讨论】:

  • 您遍历foreach 循环内的所有计算机,并且仅在迭代完成后检查Until 条件。由于ReadCount 属性基于一,$readCount 将等于$count,因此您的Until 条件永远不会满足。

标签: powershell do-loops


【解决方案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
}

【讨论】:

  • 好吧,我不希望它遍历整个列表,我只想要除最后一台以外的所有计算机。基本上我想让服务在一台计算机上运行。
  • 哦,太好了,我没有意识到有一个-skiplast .... 好的。但是你能解释一下为什么我在“直到”中的条件为真,但循环仍在继续。在旁注中,我将 $readcount 移到了 foreach 循环之外,它至少允许循环停止......但是即使 -eq 1,它仍然会命中 foreach 并在最后一台计算机上重新启动服务。
  • 是的,我再次编辑了答案并添加了解释。
  • 无论哪种方式我都接受您的回答,因为它至少可以完成这项工作。我只是对“直到”没有按预期工作感到沮丧。
  • @jisaak Get-ContentReadCount 属性添加到返回的对象。
猜你喜欢
  • 1970-01-01
  • 2017-02-03
  • 2012-09-16
  • 2020-11-29
  • 2021-12-24
  • 1970-01-01
  • 2016-05-02
  • 2016-04-12
  • 2018-06-29
相关资源
最近更新 更多