Exit


Definition: Exits a block of Do ...Loop, For...Next, Function, or Subcode.

 

In Windows PowerShell you can “prematurely” break out of a loop by using the breakcommand; this is equivalent to using the Exit Do or Exit Forstatement in VBScript. For example, the following Windows PowerShell script creates an array ($a) containing 9 values. The script then uses a For Each loop to enumerate all the items in that array; however, if any of those items is equal to 3 – if ($ ieq3)– then the break command is used to exit the loop right then and there. The script itself looks like this:

 

$a = 1 ,2,3,4,5,6,7,8,9

foreach ($ iin $a)
{
    if ($ i- eq3)
    {
        break
    }
    else
    {
        $ i
    }
}

 

And here’s what you get back when you run the script:

 

1
2