Powershell: "break" seems to end whole program, not just a loop?

1.7k views Asked by At

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.

1

There are 1 answers

0
Varvara Kalinina On BEST ANSWER

ForEach-Object and foreach loop are different. If you use the latter everything should work as you expect.

foreach ($n in (1..10)){
    $n
    if(($n % 3) -eq 0)
    {
     "wow";
     break;
    }
}

"hello"

The output would be

1
2
3
wow
hello

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 the process block inside. The foreach is a statement. Naturally, break can behave differently.