Fiddle Freak
Fiddle Freak

Reputation: 2041

Break out of inner loop only in nested loop

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?

Upvotes: 8

Views: 6852

Answers (2)

K. Frank
K. Frank

Reputation: 1448

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"

Upvotes: 3

boeprox
boeprox

Reputation: 1868

You won't be able to use a named loop with ForEach-Object, but can do it using the ForEach keyword instead like so:

$OuterLoop = 1..10
$InnerLoop = 25..50

$OuterLoop | ForEach-Object {
    Write-Verbose "[OuterLoop] $($_)" -Verbose
    :inner
    ForEach ($Item in $InnerLoop) {
        Write-Verbose "[InnerLoop] $($Item)" -Verbose
        If ($Item -eq 30) {
            Write-Warning 'BREAKING INNER LOOP!'
            BREAK inner
        }
    }
}

Now whenever it gets to 30 on each innerloop, it will break out to the outer loop and continue on.

Upvotes: 11

Related Questions