Nested ForEach() in PowerShell Nested ForEach() in PowerShell powershell powershell

Nested ForEach() in PowerShell


Use a label as described in get-help about_break:

A Break statement can include a label. If you use the Break keyword witha label, Windows PowerShell exits the labeled loop instead of exiting thecurrent loop

Like so,

foreach ($objectA in @("a", "e", "i")) {    "objectA: $objectA"    :outer    foreach ($objectB in @("a", "b", "c", "d", "e")) {       if ($objectB -eq $objectA) {           "hit! $objectB"           break :outer       } else { "miss! $objectB" }    }}#Output:objectA: ahit! aobjectA: emiss! amiss! bmiss! cmiss! dhit! eobjectA: imiss! amiss! bmiss! cmiss! dmiss! e


Here's an example using break/continue. Reverse the test in the inner loop, and use Continue to keep the loop going until the test fails. As soon as it gets a hit, it will break the inner loop, and go back to the next object in the outer loop.

foreach ($objectA in @("a", "e", "i"))   {    "objectA: $objectA"    foreach ($objectB in @("a", "b", "c", "d", "e")) {       if ($objectB -ne $objectA)         {           "miss! $objectB"           continue         }     else {           "hit!  $objectB"            break          }   }}objectA: ahit!  aobjectA: emiss! amiss! bmiss! cmiss! dhit!  eobjectA: imiss! amiss! bmiss! cmiss! dmiss! e


I would use a Do..until loop - its intended use is exactly what you're describing.

Function checkLists() {  ForEach ($objectA in $listA) {    $Counter = 0    Do {        $ObjectB = $listB[$Counter]        #other stuff    }    #Keep going until we have a match or reach end of array    Until (($objectA -eq $objectB) -or (($Counter+1) -eq $Listb.count()))    }}

Here's an easy example:

#Example use of do..until$i = 1do {  $i++  write-host $i  }until ($i -eq 10)