Return from a piped foreach in function

Azureus

New Member
Hello,
I am observing a curious behavior in PowerShell 2.0. The code:

function test()
{
1,2,3 | %{if($_ -eq 2){return}else{Write-Host $_}}
}
test


outputs
1
3


while the code:

function test()
{
$a = 1,2,3
foreach($b in $a)
{
if($b -eq 2){return}else{Write-Host $b}
}
}
test


outputs
1

In the first example, why does the return statement not return from the function?
 

My Computer

M

Marco Shaw [MVP]

> -In the first example, why does the return statement not return from

> the function?
PS>help about_return

It appears you must return "something" if you want to actually see output.

Marco
 

My Computer

P

PaulChavez

I think because ForEach-Object processes each item in the pipeline, but the
foreach statement processes the collection as a whole.

So in the first function the return keyword ends processing of that one item
in the pipeline, in the second function you're breaking out of the entire
foreach statement.

Paul


"Azureus" wrote:

>
> Hello,
> I am observing a curious behavior in PowerShell 2.0. The code:
>
> -function test()
> {
> 1,2,3 | %{if($_ -eq 2){return}else{Write-Host $_}}
> }
> test-
>
> outputs
> -1
> 3-
>
> while the code:
> -
> function test()
> {
> $a = 1,2,3
> foreach($b in $a)
> {
> if($b -eq 2){return}else{Write-Host $b}
> }
> }
> test-
>
> outputs
> -1
>
> -In the first example, why does the return statement not return from
> the function?
>
>
> --
> Azureus
>
 

My Computer

Top