如果我在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
并非易事。
发布于 2011-10-14 04:51:24
因为For-Each
对象是cmdlet而不是循环,而continue
和break
不适用于它。
例如,如果您有:
$b = 1,2,3
foreach($a in $b) {
$a | foreach { if ($_ -eq 2) {continue;} else {Write-Host $_} }
Write-Host "after"
}
您将得到如下输出:
1
after
3
after
这是因为continue
应用于外部foreach循环,而不是foreach对象cmdlet。在没有循环的情况下,最外面的级别,因此会给您一个印象,它的行为类似于break
。
那么,如何获得continue
-like行为呢?一种方式当然是Where-Object:
1..100 | ?{ $_ % 7 -eq 0} | %{Write-Host $_ is a multiple of 7}
发布于 2018-07-01 08:26:22
一条简单的else
语句使其工作方式如下所示:
1..100 | ForEach-Object {
if ($_ % 7 -ne 0 ) {
# Do nothing
} else {
Write-Host "$($_) is a multiple of 7"
}
}
或在单个管道中:
1..100 | ForEach-Object { if ($_ % 7 -ne 0 ) {} else {Write-Host "$($_) is a multiple of 7"}}
但更优雅的解决方案是反转您的测试,只为成功生成输出
1..100 | ForEach-Object {if ($_ % 7 -eq 0 ) {Write-Host "$($_) is a multiple of 7"}}
https://stackoverflow.com/questions/7760013
复制相似问题