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.

2
  • possible duplicate of How to exit from ForEach-Object in PowerShell Commented Jun 10, 2015 at 9: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. Commented Jun 10, 2015 at 9:26

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.