Loops, break, and continue
The break
keyword can be used to end a loop early. The loop in the following example would continue until the value of $i
is 20
. break
is used to stop the loop when $i
reaches 10
:
for ($i = 0; $i -lt 20; $i += 2) {
Write-Host $i
if ($i -eq 10) {
break # Stop this loop
}
}
The break
keyword acts on the loop it is nested inside. In the following example, the do
loop breaks early—when the variable $i
is less than or equal to 2
and variable $k
is greater than or equal to 3
:
$i = 1 # Initial state for i
do {
Write-Host "i: $i"
$k = 1 # Reset k
while ($k -lt 5) {
Write-Host " k: $k"
$k++ # Increment k
if ($i -le 2 -and $k -ge 3) {
break
}
}
$i++ # Increment i
} while ($i -le 3)
The output of the loop is:
i: 1
k: 1
k: 2
i: 2
k: 1
k: 2
i: 3
k: 1
k: 2
k: 3
k: 4
The continue
keyword may be used to move on to...