PowerShellPracticeAndStyle icon indicating copy to clipboard operation
PowerShellPracticeAndStyle copied to clipboard

Add Gotcha :: Breaking from the pipeline

Open JohnLBevan opened this issue 6 years ago • 3 comments
trafficstars

It would be good to add a gotcha on breaking from pipelines...

i.e. People expect this:

    $found = $false
    $list | ForEach-Object {
        if ($_ -eq $searchFor) {
            $found = $true
            break
        }
    }
    if ($found){'Woo'}else{'Boo'}

to work like this:

    $found = $false
    foreach {$item in $list} {
        if ($item -eq $searchFor) {
            $found = $true
            break
        }
    }
    if ($found){'Woo'}else{'Boo'}

JohnLBevan avatar Aug 12 '19 08:08 JohnLBevan

Agree; this behavior is pretty well-known, but may cause confusion and is not intuitive. Normally, if I need break or continue in a loop, I use a language keyword (for, foreach, while, etc.) instead of ForEach-Object to avoid confusion.

Bill-Stewart avatar Aug 22 '19 17:08 Bill-Stewart

Maybe add a counter to show that they are different as you can't see it on the output in this case. Where should it be added? Under pipeline maybe?

Objections avatar Oct 11 '19 04:10 Objections

You should use return inside ForEach-Object instead of break

serjou1 avatar Jun 17 '20 05:06 serjou1