Simply use the return
instead of the continue
. This return
returns from the script block which is invoked by ForEach-Object
on a particular iteration, thus, it simulates the continue
in a loop.
1..100 | ForEach-Object {
if ($_ % 7 -ne 0 ) { return }
Write-Host "$($_) is a multiple of 7"
}
There is a gotcha to be kept in mind when refactoring. Sometimes one wants to convert a foreach
statement block into a pipeline with a ForEach-Object
cmdlet (it even has the alias foreach
that helps to make this conversion easy and make mistakes easy, too). All continue
s should be replaced with return
.
P.S.: Unfortunately, it is not that easy to simulate break
in ForEach-Object
.