I have this script:
1..10|%{
$_
if(($_ % 3) -eq 0)
{
"wow"
break
}
}
"hello"
I expect from 1 to 10, when meeting 3 it prints"wow", and finally "hello" But actual output is:
1
2
3
kkk
So "break" seems to break not the %{} loop in pipeline, but broke the whole program? How can I break in the loop, while keep executing later statements?
Thank you.
ForEach-Object
andforeach
loop are different. If you use the latter everything should work as you expect.The output would be
UPD: You can read some helpful info about the differences here. The main thing to point attention to is that the
Foreach-Object
is integrated into the pipeline, it's basically a function with theprocess
block inside. Theforeach
is a statement. Naturally,break
can behave differently.