PowerShell documentation error – loop labels

I’ve been banging my head on a problem with a script I’m writing. I want to stop executing an inner loop and resume with the next iteration of an outer loop. In Perl, I’d use a next statement with a loop label. In PowerShell, the analogous statement is continue, and loop labels are supported, as described in the about_Break help document.

I finally wrote simplified test code, following the documentation carefully. However, the documentation is wrong. It indicates that the break or continue statement should include the colon in the loop label. This doesn’t throw an error, but it executes as though the label isn’t present at all. The code below includes the colon.

$VerbosePreference = 'Continue'

write-warning 'There should be no output; the outer loop should be exited during first iteration'
:outer foreach ($a in ('red','green') ) {
    write-verbose "Outer loop"

    :inner foreach ($b in ('red','blue','green') ) {
        write-verbose "Inner loop"
        write-verbose "`$a is $a ; `$b is $b"
        if ( $a -eq $b ) {
            break :outer
        "$a $b"

Then cracked my copy of PowerShell in Action and saw that the loop label does not include the colon, just like Perl. Remove the colon and everything is good. Wish it hadn’t taken me hours to work it out.


Sr. System Administrator at the University of Vermont

1 Comment

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.