Break out of inner loop only in nested loop

Viewed 5519

I'm trying to implement a break so I don't have to continue to loop when I got the result xxxxx times.

$baseFileCsvContents | ForEach-Object {
    # Do stuff
    $fileToBeMergedCsvContents | ForEach-Object {
        If ($_.SamAccountName -eq $baseSameAccountName) {
            # Do something
            break
        }
        # Stop doing stuff in this For Loop
    }
    # Continue doing stuff in this For Loop
}

The problem is, that break is exiting both ForEach-Object loops, and I just want it to exit the inner loop. I have tried reading and setting flags like :outer, however all I get is syntax errors.

Anyone know how to do this?

2 Answers

Using the return keyword works, as "ForEach-Object" takes a scriptblock as it's parameter and than invokes that scriptblock for every element in the pipe.

    1..10 | ForEach-Object {
        $a = $_
        1..2 | ForEach-Object {
            if($a -eq 5 -and $_ -eq 1) {return}
            "$a $_"
        }
        "---"
    }

Will skip "5 1"

Related