February 2019
Intermediate to advanced
626 pages
15h 51m
English
break can be used to end a loop early. The loop in the following example would continue to 20; break is used to stop the loop at 10:
for ($i = 0; $i -lt 20; $i += 2) { Write-Host $i
if ($i -eq 10) { break # Stop this loop
}
}
break acts on the loop it is nested inside. In the following example, the inner loop breaks early when the i variable is less than or equal to 2:
PS> $i = 1 # Initial state for iPS> while ($i -le 3) {>> 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>> }i: 1k: 1k: 2i: 2k: 1k: 2i: 3k: 1k: 2k: 3k: 4
The continue keyword may be used to move on to the next iteration of a loop immediately. ...
Read now
Unlock full access