Loops, break, and continue
The break and continue keywords can be used to control the flow within a loop, typically to exit earlier than a condition at the start or end of the loop would normally permit.
In the example below, a set of random numbers is created, then the foreach loop is used to find the first instance of any number greater than 10:
$randomNumbers = Get-Random -Count 30 -Minimum 1 -Maximum 30
foreach ($number in $randomNumbers) {
if ($number -gt 10) {
break
}
}
$number
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 the variable $k is greater than or equal to 3:
$i = 1 # Initial...