Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit from ForEach-Object in PowerShell

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?

like image 590
Michael Sync Avatar asked Apr 23 '12 09:04

Michael Sync


People also ask

How do I exit foreach in PowerShell?

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.

How do you exit a PowerShell script?

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.

What does $_ do in PowerShell?

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.

What does exit do in 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.


1 Answers

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.

like image 125
smeltplate Avatar answered Sep 18 '22 15:09

smeltplate