Converting VBScript's Exit Statement

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

Exit

In Windows PowerShell you can “prematurely” break out of a loop by using the break command; this is equivalent to using the Exit Do or Exit For statement 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 ($i -eq 3) - 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 ($i in $a) 
{
    if ($i -eq 3)
    {
        break
    } 
    else 
    {
        $i
    }
}

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

1
2

Return to the VBScript to Windows PowerShell home page