Why does 'continue' behave like 'break' in a Foreach-Object?

后端 未结 4 1336
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 04:25

If I do the following in a PowerShell script:

$range = 1..100
ForEach ($_ in $range) {
    if ($_ % 7 -ne 0 ) { continue; }
    Write-Host \"$($_) is a multi         


        
4条回答
  •  旧巷少年郎
    2020-11-27 04:46

    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 continues should be replaced with return.

    P.S.: Unfortunately, it is not that easy to simulate break in ForEach-Object.

提交回复
热议问题