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

后端 未结 4 1349
被撕碎了的回忆
被撕碎了的回忆 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:48

    A simple else statement makes it work as in:

    1..100 | ForEach-Object {
        if ($_ % 7 -ne 0 ) {
            # Do nothing
        } else {
            Write-Host "$($_) is a multiple of 7"
        }
    }
    

    Or in a single pipeline:

    1..100 | ForEach-Object { if ($_ % 7 -ne 0 ) {} else {Write-Host "$($_) is a multiple of 7"}}
    

    But a more elegant solution is to invert your test and generate output for only your successes

    1..100 | ForEach-Object {if ($_ % 7 -eq 0 ) {Write-Host "$($_) is a multiple of 7"}}
    

提交回复
热议问题