How to exit from ForEach-Object in PowerShell

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

    Since ForEach-Object is a cmdlet, break and continue will behave differently here than with the foreach keyword. Both will stop the loop but will also terminate the entire script:

    break:

    0..3 | foreach {
        if ($_ -eq 2) { break }
        $_
    }
    echo "Never printed"
    
    # OUTPUT:
    # 0
    # 1
    

    continue:

    0..3 | foreach {
        if ($_ -eq 2) { continue }
        $_
    }
    echo "Never printed"
    
    # OUTPUT:
    # 0
    # 1
    

    So far, I have not found a "good" way to break a foreach script block without breaking the script, except "abusing" exceptions:

    throw:

    try {
        0..3 | foreach {
            if ($_ -eq 2) { throw }
            $_
        }
    } catch { }
    echo "End"
    
    # OUTPUT:
    # 0
    # 1
    # End
    

    The alternative (which is not always possible) would be to use the foreach keyword:

    foreach:

    foreach ($_ in (0..3)) {
        if ($_ -eq 2) { break }
        $_
    }
    echo "End"
    
    # OUTPUT:
    # 0
    # 1
    # End
    

提交回复
热议问题