Returning a value from within a ForEach in Powershell Returning a value from within a ForEach in Powershell powershell powershell

Returning a value from within a ForEach in Powershell


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:

$a.ForEach{ return $_ }

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):

    ForEach ($item In $a) { return $item }
  2. Select the first value returned from all the scriptblocks:

    $a.ForEach{ return $_ } | Select -First 1