1

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.

vik santata
  • 2,989
  • 8
  • 30
  • 52
  • possible duplicate of [How to exit from ForEach-Object in PowerShell](http://stackoverflow.com/questions/10277994/how-to-exit-from-foreach-object-in-powershell) – Martin Brandl Jun 10 '15 at 09:16
  • It should print "wow" at 6 and 9 also, but nevertheless, `break` does exit the script altogether. `return` doesn't help either, so this is no duplicate. – Vesper Jun 10 '15 at 09:26

1 Answers1

7

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.

Varvara Kalinina
  • 2,043
  • 19
  • 29