Returning a value from within a ForEach in Powershell

11,042

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
    
Share:
11,042
Ben Power
Author by

Ben Power

Developer in Test, specialist in retrofitting test automation. CI, CD, DevOps, Performance testing, anything involving looking at a lots of code and dealing with complex technical problems.

Updated on June 13, 2022

Comments

  • Ben Power
    Ben Power almost 2 years

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

    function ReturnStuff{
        $a=1,2,3,4,5
        $a.ForEach{
            return $_
        }
    }
    
    ReturnStuff
    

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

  • Ben Power
    Ben Power almost 8 years
    Wow, that's one hell of a trap for newbies! Thanks!
  • mhenry1384
    mhenry1384 over 6 years
    Doesn't make any sense to me why they work differently. Isn't the ForEach loop (option #1) also being called with a parameter which is a scriptblock?