Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a value from within a ForEach in Powershell

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?

like image 314
Ben Power Avatar asked Jun 01 '16 01:06

Ben Power


People also ask

How do you exit an object in foreach?

The Break statement is used to exit a looping statement such as a Foreach, For, While, or Do loop. When present, the Break statement causes Windows PowerShell to exit the loop. The Break statement can also be used in a Switch statement.

How do I break a foreach loop in PowerShell?

When a break statement appears in a loop, such as a foreach , for , do , or while loop, PowerShell immediately exits the loop. A break statement can include a label that lets you exit embedded loops. A label can specify any loop keyword, such as foreach , for , or while , in a script.

How do I return a value from a PowerShell script?

The return keyword exits a function, script, or script block. It can be used to exit a scope at a specific point, to return a value, or to indicate that the end of the scope has been reached.

Can a PowerShell function return a value?

Because we can return values from a PowerShell function, the value of the return keyword might not immediately be evident. The difference between returning values with Write-Output and the return keyword is using the return keyword exits the current scope.


1 Answers

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
    
like image 96
xXhRQ8sD2L7Z Avatar answered Oct 12 '22 21:10

xXhRQ8sD2L7Z