176coding
176coding

Reputation: 3069

continue statement confusing in powershell, looks like break statement

My code looks like:

1..10 | % {
    $i=$_
    10..20 | % {
        if ($_ -gt 12) {
            continue
        }
       Write-Host $i $_
    }
}

Why the output is:

1 10
1 11
1 12

It seems the continue statement in PoweShell is not different with other language, why PowerShell is designed like this?

If I change the continue to return, then I get the expect result.

Upvotes: 1

Views: 437

Answers (1)

Martin Brandl
Martin Brandl

Reputation: 58981

As PeterSerAI pointed out in his comment, you don't use a loop in your code, you are instead using the Foreach-Object cmdlet which is different.

Just use a foreach loop instead:

foreach($obj in 1.. 10)
{
    $i = $obj
    foreach($obj2 in 10 ..20) {
        if ($obj2 -gt 12) {
            continue
        }
       Write-Host $obj $obj2
    }
}

Upvotes: 2

Related Questions