PowerShellPracticeAndStyle
PowerShellPracticeAndStyle copied to clipboard
Add Gotcha :: Breaking from the pipeline
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'}
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.
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?
You should use return inside ForEach-Object instead of break