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?

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Cooper.Wu
  • 4,335
  • 8
  • 34
  • 42

2 Answers2

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 $_"
}
manojlds
  • 290,304
  • 63
  • 469
  • 417
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"
}
CB.
  • 58,865
  • 9
  • 159
  • 159