Why does continue in ForEach-Object operate like break?

10,091

Solution 1

Because continue and break are meant for loops and foreach-object is a cmdlet. The behaviour is not really what you expect, because it is just stopping the entire script ( add a statement after the original code and you will see that that statement doesn't run)

To get similar effect as continue used in a foreach loop, you may use return:

$arr = @(1..10)
$arr | ForEach-Object {
    if ($_ -eq 5){ return}
    "output $_"
}

Solution 2

it is because the continue is applied to the foreach loop (foreach $item in $collection) and not in the foreach-object cmdlet. try this:

$arr = @(1..10)
$arr | ForEach-Object {
    if ($_ -eq 5){ return}
    "output $_"
}

and this:

$arr = @(1..10)
 ForEach ($i in $arr) {
    if ($i -eq 5){ continue}
    "output $i"
}
Share:
10,091
Cooper.Wu
Author by

Cooper.Wu

Updated on October 22, 2022

Comments

  • Cooper.Wu
    Cooper.Wu less than a minute
    $arr = @(1..10)
    $arr | ForEach-Object {
        if ($_ -eq 5) { continue }
        "output $_"
    }
    

    Result:

    output 1
    output 2
    output 3
    output 4
    

    $arr = @(1..10)
    $arr | ForEach-Object {
        if ($_ -eq 5) { break }
        "output $_"
    }
    

    Result:

    output 1
    output 2
    output 3
    output 4
    

    Why?