How to exit from ForEach-Object in PowerShell

前端 未结 9 1795
北海茫月
北海茫月 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:10

    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.

提交回复
热议问题