Returning a value from within a ForEach in Powershell

Question:

This seems really basic, but I can’t see how or why it behaves this way:

Why does this give me:
1
2
3
4
5
instead of just 1?

Answer:

It looks like you are calling ForEach (a function in [System.Array]) with a parameter which is a scriptblock. Essentially, you are defining and returning { Return $_ } every iteration of the loop.

This means ReturnStuff will capture output each time, and because this function does nothing with the output of this line, all the output is returned:

This behavior is similar to $a | Foreach-Object { return $_ }

So what to do?

  1. Use a ForEach loop instead (not to be confused with Foreach-Object):
  2. Select the first value returned from all the scriptblocks:

Source:

Returning a value from within a ForEach in Powershell by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply