如果我在PowerShell脚本中执行以下操作:
$range = 1..100
ForEach ($_ in $range) {
if ($_ % 7 -ne 0 ) { continue; }
Write-Host "$($_) is a multiple of 7"
}
我得到了以下内容的预期输出:
7 is a multiple of 7
14 is a multiple of 7
21 is a multiple of 7
28 is a multiple of 7
35 is a multiple of 7
42 is a multiple of 7
49 is a multiple of 7
56 is a multiple of 7
63 is a multiple of 7
70 is a multiple of 7
77 is a multiple of 7
84 is a multiple of 7
91 is a multiple of 7
98 is a multiple of 7
但是,如果我使用管道和ForEach-Object
,continue
似乎会跳出管道循环。
1..100 | ForEach-Object {
if ($_ % 7 -ne 0 ) { continue; }
Write-Host "$($_) is a multiple of 7"
}
我是否可以在仍然使用ForEach--like的同时获得一个continue
对象行为,这样我就不必中断我的管道了?
发布于 2011-10-14 14:07:43
只需使用return
而不是continue
。此return
从ForEach-Object
在特定迭代中调用的脚本块返回,因此,它在循环中模拟continue
。
1..100 | ForEach-Object {
if ($_ % 7 -ne 0 ) { return }
Write-Host "$($_) is a multiple of 7"
}
在重构时,有一个问题需要牢记。有时,人们希望使用ForEach-Object
cmdlet将foreach
语句块转换为管道(它甚至具有别名foreach
,这有助于简化转换,也容易出错)。所有continue
都应替换为return
。
附言:不幸的是,在ForEach-Object
中模拟break
并非易事。
https://stackoverflow.com/questions/7760013
复制相似问题