Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does continue in ForEach-Object operate like break? [duplicate]

Tags:

powershell

$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?

like image 626
Cooper.Wu Avatar asked Mar 23 '12 06:03

Cooper.Wu


2 Answers

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 $_"
}
like image 183
manojlds Avatar answered Sep 21 '22 15:09

manojlds


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"
}
like image 39
CB. Avatar answered Sep 21 '22 15:09

CB.