Break And Continue
Part of the PowerShell Basics section of Coddy's PowerShell journey. Lesson 19 of 28.
break leaves a loop at once. continue skips the rest of the current round and starts the next one:
foreach ($n in 1..10) {
if ($n % 2 -eq 0) { continue }
if ($n -gt 7) { break }
Write-Output $n
}1
3
5
71..10 is a range: the array of the numbers 1 to 10. Even numbers are skipped by continue, and the loop stops at 9 because of break.
while ($true) loops forever, so it needs a break. It fits input that ends with a marker word:
while ($true) {
$item = Read-Host "Item"
if ($item -eq "end") { break }
Write-Output "Added $item"
}Challenge
EasyAdd up numbers typed one per line until the word done, skipping negative numbers.
- In a
while ($true)loop, read a line with the promptNumber. - If the line is
done(in any case), leave the loop withbreak. - If the number is negative, count it as skipped and go to the next round with
continue. - Otherwise add it to the sum.
- After the loop, print
Sum:and the sum, thenSkipped:and how many numbers were skipped.
With the input 5, -2, 7 and done, your script prints:
Number: 5
Number: -2
Number: 7
Number: done
Sum: 12
Skipped: 1Try it yourself
$sum = 0
$skipped = 0
# Read numbers until done, skipping negative ones
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in PowerShell Basics
5Project: Password Checker
Project OverviewLength Check