$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?
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 $_"
}
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With