PowerShell While Loops
A while loop repeats a block of code while a condition stays true. The loop checks the condition before every pass.
Count up with while
Start a counter at zero. Add one on every pass until the counter reaches three.
$count = 0
while ($count -lt 3) {
$count = $count + 1
$count
}Count down with while
A while loop can count down too. Print the number first, then take one away.
$n = 3
while ($n -gt 0) {
$n
$n = $n - 1
}Grow a value with while
The condition can test any value, not just a counter. Here the value doubles on every pass.
$total = 1
while ($total -lt 10) {
$total = $total * 2
$total
}Example
$sum = 0
$i = 1
while ($i -le 5) {
$sum = $sum + $i
$i = $i + 1
}
$sumKey points
- While loop: a loop that repeats while its condition is true.
- Condition: the test at the top of the loop that decides whether it runs again.
- Counter: a variable that counts passes and moves the loop toward its end.
- Use a while loop when you do not know in advance how many passes you need.
- The loop stops as soon as its condition becomes false.
In this example, the counter $i starts at 1 and the total $sum starts at 0. While $i is no more than 5, the loop adds $i to $sum and then adds 1 to $i. When $i reaches 6 the condition is false, the loop stops, and the final total prints.
Note
a loop whose condition never becomes false runs forever, so always change the counter inside the loop.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does this script print? $n = 0; while ($n -lt 2) { $n = $n + 1; $n }