If I do the following in a PowerShell script:
$range = 1..100
ForEach ($_ in $range) {
if ($_ % 7 -ne 0 ) { continue; }
Write-Host "$($_) is a multiple of 7"
}
I get the expected output of:
7 is a multiple of 7
14 is a multiple of 7
21 is a multiple of 7
28 is a multiple of 7
35 is a multiple of 7
42 is a multiple of 7
49 is a multiple of 7
56 is a multiple of 7
63 is a multiple of 7
70 is a multiple of 7
77 is a multiple of 7
84 is a multiple of 7
91 is a multiple of 7
98 is a multiple of 7
However, if I use a pipeline and ForEach-Object, continue seems to break out of the pipeline loop.
1..100 | ForEach-Object {
if ($_ % 7 -ne 0 ) { continue; }
Write-Host "$($_) is a multiple of 7"
}
Can I get a continue-like behavior while still doing ForEach-Object, so I don’t have to breakup my pipeline?
Simply use the
returninstead of thecontinue. Thisreturnreturns from the script block which is invoked byForEach-Objecton a particular iteration, thus, it simulates thecontinuein a loop.There is a gotcha to be kept in mind when refactoring. Sometimes one wants to convert a
foreachstatement block into a pipeline with aForEach-Objectcmdlet (it even has the aliasforeachthat helps to make this conversion easy and make mistakes easy, too). Allcontinues should be replaced withreturn.P.S.: Unfortunately, it is not that easy to simulate
breakinForEach-Object.