为什么 ForEach-Object 中的 continue 像 break 一样操作? [英] Why does continue in ForEach-Object operate like break?

查看:76
本文介绍了为什么 ForEach-Object 中的 continue 像 break 一样操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$arr = @(1..10)$arr |ForEach-Object {if ($_ -eq 5) { 继续 }输出$_"}

结果:

<前>输出 1输出 2输出 3输出 4

<小时>

$arr = @(1..10)$arr |ForEach-Object {如果 ($_ -eq 5) { 中断 }输出$_"}

结果:

<前>输出 1输出 2输出 3输出 4

为什么?

解决方案

因为 continuebreak 用于循环和 foreach-object是一个 cmdlet.该行为并不是您所期望的,因为它只是停止了整个脚本(在原始代码后添加一条语句,您将看到该语句没有运行)

为了获得与在 foreach 循环中使用 continue 类似的效果,您可以使用 return:

$arr = @(1..10)$arr |ForEach-Object {如果 ($_ -eq 5){ 返回}输出$_"}

$arr = @(1..10)
$arr | ForEach-Object {
    if ($_ -eq 5) { continue }
    "output $_"
}

Result:

output 1
output 2
output 3
output 4


$arr = @(1..10)
$arr | ForEach-Object {
    if ($_ -eq 5) { break }
    "output $_"
}

Result:

output 1
output 2
output 3
output 4

Why?

解决方案

Because continue and break are meant for loops and foreach-object is a cmdlet. The behaviour is not really what you expect, because it is just stopping the entire script ( add a statement after the original code and you will see that that statement doesn't run)

To get similar effect as continue used in a foreach loop, you may use return:

$arr = @(1..10)
$arr | ForEach-Object {
    if ($_ -eq 5){ return}
    "output $_"
}

这篇关于为什么 ForEach-Object 中的 continue 像 break 一样操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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