Menu
CoddyTech

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
7

1..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 icon

Challenge

Easy

Add up numbers typed one per line until the word done, skipping negative numbers.

  1. In a while ($true) loop, read a line with the prompt Number.
  2. If the line is done (in any case), leave the loop with break.
  3. If the number is negative, count it as skipped and go to the next round with continue.
  4. Otherwise add it to the sum.
  5. After the loop, print Sum: and the sum, then Skipped: 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: 1

Try it yourself

$sum = 0
$skipped = 0
# Read numbers until done, skipping negative ones
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in PowerShell Basics