Alex Rivera | Logout

Why does continue in ForEach-Object operate like break?

Asked 2012-03-23T06:57:41.313
8
$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?

Edit
Report

2 Answers

18

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 $_"
}
answered 2012-03-23T07:04:36.617
6

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"
}
answered 2012-03-23T07:11:32.043

Your Answer