How to exit from ForEach-Object in PowerShell

前端 未结 9 1808
北海茫月
北海茫月 2020-11-27 20:30

I have the following code:

$project.PropertyGroup | Foreach-Object {
    if($_.GetAttribute(\'Condition\').Trim() -eq $propertyGroupConditionName.Trim()) {
           


        
9条回答
  •  一向
    一向 (楼主)
    2020-11-27 21:05

    You have two options to abruptly exit out of ForEach-Object pipeline in PowerShell:

    1. Apply exit logic in Where-Object first, then pass objects to Foreach-Object, or
    2. (where possible) convert Foreach-Object into a standard Foreach looping construct.

    Let's see examples: Following scripts exit out of Foreach-Object loop after 2nd iteration (i.e. pipeline iterates only 2 times)":

    Solution-1: use Where-Object filter BEFORE Foreach-Object:

    [boolean]$exit = $false;
    1..10 | Where-Object {$exit -eq $false} | Foreach-Object {
         if($_ -eq 2) {$exit = $true}    #OR $exit = ($_ -eq 2);
         $_;
    }
    

    OR

    1..10 | Where-Object {$_ -le 2} | Foreach-Object {
         $_;
    }
    

    Solution-2: Converted Foreach-Object into standard Foreach looping construct:

    Foreach ($i in 1..10) { 
         if ($i -eq 3) {break;}
         $i;
    }
    

    PowerShell should really provide a bit more straightforward way to exit or break out from within the body of a Foreach-Object pipeline. Note: return doesn't exit, it only skips specific iteration (similar to continue in most programming languages), here is an example of return:

    Write-Host "Following will only skip one iteration (actually iterates all 10 times)";
    1..10 | Foreach-Object {
         if ($_ -eq 3) {return;}  #skips only 3rd iteration.
         $_;
    }
    

    HTH

提交回复
热议问题