为什么“继续"在 Foreach 对象中表现得像“中断"? [英] Why does 'continue' behave like 'break' in a Foreach-Object?

查看:25
本文介绍了为什么“继续"在 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-Objectcontinue 似乎会跳出管道循环.

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.这个 return 从脚本块返回,该脚本块由 ForEach-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天全站免登陆