For And While
Part of the PowerShell Basics section of Coddy's PowerShell journey. Lesson 18 of 28.
A for loop counts. Its parentheses hold three parts: the start, the condition that keeps the loop going, and the step after each round:
for ($i = 1; $i -le 3; $i++) {
Write-Output "Lap $i"
}Lap 1
Lap 2
Lap 3$i-- counts down instead. A while loop repeats as long as its condition is True, so it fits when you do not know the number of rounds in advance:
$money = 100
$years = 0
while ($money -lt 150) {
$money = $money * 1.1
$years++
}
Write-Output "Years: $years"This prints Years: 5. Something inside a while loop must change the condition, or the loop never ends and the run times out.
Challenge
EasyWrite a launch countdown, then count how many times the start number can be halved.
- Read a whole number with the prompt
Start. - With a
forloop, print every number from the start number down to 1, one per line, then printLiftoff!. - With a
whileloop, halve the start number (rounding down with[math]::Floor()) until it is 1 or less, counting the halvings. PrintHalvings:and the count.
With the input 5, your script prints (5 becomes 2, then 1: two halvings):
Start: 5
5
4
3
2
1
Liftoff!
Halvings: 2Try it yourself
$n = [int](Read-Host "Start")
# Count down with a for loop, then count the halvings with a while loop
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