Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 514
Fiddle Freak Avatar asked Mar 16 '16 02:03

Fiddle Freak


Video Answer


1 Answers

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.

like image 58
boeprox Avatar answered Oct 05 '22 01:10

boeprox