8

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 2

11

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Bummer. There is a lot of complicated stuff going on within ForEach-Object loops (actual code can be viewed here - stackoverflow.com/questions/36019303/…). If I were to change ForEach-Object to ForEach, it will break the script. Looks like I won't be able to use the break...
Actually I take that back, I was able to change it to a ForEach, and it worked. Thanks :)
I get + FullyQualifiedErrorId : CommandNotFoundException with :inner in PS5
3

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"

1 Comment

That works in PS5 whereas the other answer with namedloop and foreach instead of foreach-object does not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.