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 i
PS> 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: 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 the next iteration of a loop immediately. For example, the following loop executes a subset of the loop body when the value of the i variable is less than 2:
for ($i = 0; $i -le 5; $i++) { Write-Host $i if ($i -lt 2) { continue # Continue to the next iteration } Write-Host "Remainder when $i is divided by 2 is $($i % 2)" }