I was playing around with a for loop I have in one of my functions, and noticed an oddity. If I do something like this:
foreach ($a in 1..40) {
try {
Add-Content -Path $Path -Value $Content -ErrorAction Stop
break
} catch {
Start-Sleep -Milliseconds 250
}
}
It works as expected, breaking out of the foreach loop and continuing the function. I can even be specific and assign the loop a label, and the break specifically from that label. But if I shorthand it:
(1..40) | % {
try {
Add-Content -Path $Path -Value $Content -ErrorAction Stop
break
} catch {
Start-Sleep -Milliseconds 250
}
}
The break not only takes me out of the loop, but out of the function and the whole script. I cannot assign a label to the shorthand version of the loop statement, and have yet to find a way to break only out of the foreach loop in this case. Yes, I know I should write things out rather than shorthand, I am just curious if this is intended behavior or not.