How to exit from ForEach-Object in PowerShell

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

    If you insist on using ForEach-Object, then I would suggest adding a "break condition" like this:

    $Break = $False;
    
    1,2,3,4 | Where-Object { $Break -Eq $False } | ForEach-Object {
    
        $Break = $_ -Eq 3;
    
        Write-Host "Current number is $_";
    }
    

    The above code must output 1,2,3 and then skip (break before) 4. Expected output:

    Current number is 1
    Current number is 2
    Current number is 3
    

提交回复
热议问题