Loops and labels
In PowerShell, a loop can be given a label. The label may be used with break
and continue
to define a specific point loop to act on.The label is written before the loop keyword (for
, while
, do
, or foreach
) and is preceded by a colon character. For example:
:ThisIsALabel foreach ($value in 1..10) {
$value
}
The label may be placed directly before the loop keyword or on the line above. For example:
:ThisIsALabel
foreach ($value in 1..10) {
$value
}
The example above will work when saved as a script, but if it is pasted into the label will be split from the loop. Holding shift and return between the label and loop is required when typing the example into the console.White space may appear between the label and the loop keyword.The label is used with break
or continue
and can be useful when one loop is nested inside another. The label name is written after the break
or continue
keyword without the colon.
:outerLoop for ($i = 1; $i -le 5; $i++) {
:innerLoop...