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?
First of all,
Foreach-Objectis not an actual loop and callingbreakin it will cancel the whole script rather than skipping to the statement after it.Conversely,
breakandcontinuewill work as you expect in an actualforeachloop.Item #1. Putting a
breakwithin theforeachloop does exit the loop, but it does not stop the pipeline. It sounds like you want something like this:Item #2. PowerShell lets you modify an array within a
foreachloop over that array, but those changes do not take effect until you exit the loop. Try running the code below for an example.I can’t comment on why the authors of PowerShell allowed this, but most other scripting languages (Perl, Python and shell) allow similar constructs.