I have the following code:
$project.PropertyGroup | Foreach-Object { if($_.GetAttribute('Condition').Trim() -eq $propertyGroupConditionName.Trim()) { $a = $project.RemoveChild($_); Write-Host $_.GetAttribute('Condition')"has been removed."; } };
Question #1: How do I exit from ForEach-Object? I tried using "break" and "continue", but it doesn't work.
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?
The Break statement is used to exit a looping statement such as a Foreach, For, While, or Do loop. When present, the Break statement causes Windows PowerShell to exit the loop. The Break statement can also be used in a Switch statement.
Open a PowerShell console session, type exit , and press the Enter key. The PowerShell console will immediately close. This keyword can also exit a script rather than the console session.
The $_ is a variable or also referred to as an operator in PowerShell that is used to retrieve only specific values from the field. It is piped with various cmdlets and used in the “Where” , “Where-Object“, and “ForEach-Object” clauses of the PowerShell.
Exit Keyword If the Exit keyword is used in the functions and the main script, it closes everything and you may not get a chance to see the output in the console if not stored before the Exit Keyword is used. You can't see the above output because as soon as you run the command it terminates the script.
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.
Conversely, break
and continue
will work as you expect in an actual foreach
loop.
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 } }
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
I can't comment on why the authors of PowerShell allowed this, but most other scripting languages (Perl, Python and shell) allow similar constructs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With