Break from loops

I have a Loop2 inside Loop1. What command can be used to replace 'GOTO Loop1'  to continue Loop1 without executing command3 and command4 when If condition is met?

1..10 | % { # Loop 1

         command1

         command2

         array1, array2, array3 | % { # Loop2

              If ( $_ -contains 'abc' ) { GOTO Loop1 }

         }

         command3

         command4

}


  • Edited by Ian3 8 hours 48 minutes ago
October 29th, 2014 9:16pm

I have not tested but "get-help about_break" explains about the labeled loops.

You can nest many labeled loops, as shown in the following schematic
example.


    :red while (<condition1>)
    {
        :yellow while (<condition2>)
        {
            while (<condition3>)
            {
                if ($a) {break}
                if ($b) {break :red}
                if ($c) {break :yellow}
            }
            # After innermost loop
        }
            # After "yellow" loop
    }
            # After "red" loop


  • Edited by hysh_00 8 hours 21 minutes ago
Free Windows Admin Tool Kit Click here and download it now
October 29th, 2014 9:53pm

I did below but got ":LOOP1 : The term ':LOOP1' is not recognized...."

:LOOP1 1..10 | % { # Loop 1

October 29th, 2014 10:17pm

Looks like you have to rewrite the loop in foreach like this.

:aa foreach($i in (1..10)){

     if($i -eq 5){

           break :aa}

 }


Free Windows Admin Tool Kit Click here and download it now
October 29th, 2014 11:10pm

$TestArray1="a","b","c"
$TestArray2="ab","ac","abc"   
$TestArray3="abd","abe","acd","ace"
$TestArray = @($TestArray1,$TestArray2,$TestArray3)

0..2 | % { # Loop 1
         "command1 $_"
         "command2 $_"
         $IsOk=$True
         $TestArray[$_] | % { # Loop2
              If ( $_ -contains 'abc' ) { $IsOK=$False }
         }
         IF ($IsOK)
         {
           "command3 $_"
           "command4 $_"
         }
}


On the first pass through loop 1 it uses TestArray1 to check variable and does command 3 & 4

On the second pass through loop 1 it uses TestArray2 to check variable and does not do commands 3 &4

On the third pass through loop 1 it uses TestArray3 to check variable and does command 3 &4

Here is output

command1 0
command2 0
command3 0
command4 0
command1 1
command2 1
command1 2
command2 2
command3 2
command4 2


October 30th, 2014 4:14am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics