如何在 PowerShell 中退出 ForEach-Object [英] How to exit from ForEach-Object in PowerShell
问题描述
我有以下代码:
$project.PropertyGroup | Foreach-Object {
if($_.GetAttribute('Condition').Trim() -eq $propertyGroupConditionName.Trim()) {
$a = $project.RemoveChild($_);
Write-Host $_.GetAttribute('Condition')"has been removed.";
}
};
问题 1:如何退出 ForEach-Object?我尝试使用break"和继续",但它不起作用.
Question #1: How do I exit from ForEach-Object? I tried using "break" and "continue", but it doesn't work.
问题 #2:我发现我可以在 foreach
循环中更改列表...我们不能像在 C# 中那样做...为什么 PowerShell 允许我们这样做?
Question #2: I found that I can alter the list within a foreach
loop... We can't do it like that in C#... Why does PowerShell allow us to do that?
推荐答案
首先,Foreach-Object
不是一个实际的循环并调用 break
将取消整个脚本而不是跳到它后面的语句.
First of all, Foreach-Object
is not an actual loop and calling break
in it will cancel the whole script rather than skipping to the statement after it.
相反,break
和 continue
将在实际的 foreach
循环中按预期工作.
Conversely, break
and continue
will work as you expect in an actual foreach
loop.
项目#1.在 foreach
循环中放置一个 break
确实会退出循环,但不会停止管道.听起来你想要这样的东西:
Item #1. Putting a break
within the foreach
loop does exit the loop, but it does not stop the pipeline. It sounds like you want something like this:
$todo=$project.PropertyGroup
foreach ($thing in $todo){
if ($thing -eq 'some_condition'){
break
}
}
第 2 项.PowerShell 允许您在该数组的 foreach
循环内修改该数组,但这些更改在您退出循环之前不会生效.尝试运行以下代码作为示例.
Item #2. PowerShell lets you modify an array within a foreach
loop over that array, but those changes do not take effect until you exit the loop. Try running the code below for an example.
$a=1,2,3
foreach ($value in $a){
Write-Host $value
}
Write-Host $a
我无法评论为什么 PowerShell 的作者允许这样做,但大多数其他脚本语言 (Perl、Python 和 shell)允许类似的结构.
I can't comment on why the authors of PowerShell allowed this, but most other scripting languages (Perl, Python and shell) allow similar constructs.
这篇关于如何在 PowerShell 中退出 ForEach-Object的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!