为什么在Foreach对象中“继续"的行为类似于“中断"? [英] Why does 'continue' behave like 'break' in a Foreach-Object?

查看:95
本文介绍了为什么在Foreach对象中“继续"的行为类似于“中断"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在PowerShell脚本中执行以下操作:

If I do the following in a PowerShell script:

$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似乎会中断管道循环.

However, if I use a pipeline and ForEach-Object, continue seems to break out of the pipeline loop.

1..100 | ForEach-Object {
    if ($_ % 7 -ne 0 ) { continue; }
    Write-Host "$($_) is a multiple of 7"
}

在仍然执行ForEach-Object的同时还能得到类似continue的行为,所以我不必中断管道吗?

Can I get a continue-like behavior while still doing ForEach-Object, so I don't have to breakup my pipeline?

推荐答案

只需使用return而不是continue.该returnForEach-Object在特定迭代中调用的脚本块返回,因此,它在循环中模拟continue.

Simply use the return instead of the continue. This return returns from the script block which is invoked by ForEach-Object on a particular iteration, thus, it simulates the continue in a loop.

1..100 | ForEach-Object {
    if ($_ % 7 -ne 0 ) { return }
    Write-Host "$($_) is a multiple of 7"
}

重构时要牢记一些陷阱.有时,有人想将foreach语句块转换为带有ForEach-Object cmdlet的管道(它甚至具有别名foreach,这也有助于简化此转换并易于出错).所有continue都应替换为return.

There is a gotcha to be kept in mind when refactoring. Sometimes one wants to convert a foreach statement block into a pipeline with a ForEach-Object cmdlet (it even has the alias foreach that helps to make this conversion easy and make mistakes easy, too). All continues should be replaced with return.

P.S .:不幸的是,要在ForEach-Object中模拟break并不是那么容易.

P.S.: Unfortunately, it is not that easy to simulate break in ForEach-Object.

这篇关于为什么在Foreach对象中“继续"的行为类似于“中断"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆