PowerShell Break and Continue Statement


Sometimes if you want to terminate you loop such as do, while, for, and foreach loop in a particular condition, here powerShell provide break statement to do such thing. For example the loop will be terminated when the particular condition is met.

$i = 1
while ($i -lt 10) {
Write-Host $i
if ($i -eq 5) {
break
}
$i++
}

$users = @("Henry", "Nicky", "Laila", "Bob", "Jane", "Dom")
foreach ($user in $users) {
if ($user -eq "Bob") {
break
}
Write-Host $user
}

Besides break statement, powerShell also provide continue statement. When the loop encounters the continue statement the control flow will return to the innermost loop immediately. Example 

$i = 0
while ($i -lt 10) {
$i++
if ($i -eq 5) { Continue }
Write-Host $i
}

$users = @("Henry", "Nicky", "Laila", "Bob", "Jane", "Dom")
foreach ($user in $users) {
if ($user -eq "Bob") {
Continue
}
Write-Host $user
}


Subscribe to receive free email updates:

0 Response to "PowerShell Break and Continue Statement "

Post a Comment