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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With