Core Skills Level: Intermediate Chapter 9: Make Scripts Decide and Repeat
Iteration: for, while, and foreach
Iteration repeats a block. For repeats a counted number of times, while repeats while a condition holds, and foreach repeats once per item in a collection.
Lesson 2 of 2 in Chapter 9: Make Scripts Decide and Repeat. Previous step in this path: Sequence and selection: if, elseif, else. 3 learning objectives, 8 examples, and a knowledge check.
Start: what you will learn
Iteration repeats a block. For repeats a counted number of times, while repeats while a condition holds, and foreach repeats once per item in a collection.
Learning objectives
- Write a for loop with a counter
- Write a while loop that ends
- Write a foreach loop over a collection
Concept in simple words
What it is: iteration means repeating a block of code, instead of writing the same lines again and again. A for loop repeats a counted number of times. A while loop repeats while a condition stays true. A foreach loop repeats once for each item in a collection, such as a list of servers. Two close relatives, do while and do until, are covered later in this lesson, because they share the same idea with one important difference: they always run at least once.
Why it works
Why it exists: almost every admin job is a job done many times. Check ten servers, not one. Retry a step a few times, not once. Process every name in a list, not just the first name. Without loops, you would copy the same block ten times, and every fix would have to be made ten times too. With a loop, you write the block once, and PowerShell runs it once per item, once per count, or once per check of the condition. That is shorter, easier to fix, and far less likely to drift out of sync.
What PowerShell is doing behind the command: a loop is a test, a block, and a return to the test. PowerShell runs the block, goes back to the test, and decides whether to run the block again. The loop ends only when the test says stop, when break leaves the loop early, or when you stop the script. The difference between loop types is what the test looks at. A for loop tests a counter. A while loop tests a condition that the body must change. A foreach loop tests whether there is another item left in the collection, and PowerShell itself moves to the next item for you.
The for loop, part by part: a for loop has three parts in its parentheses, separated by semicolons. The first part runs once at the start, and it usually sets a counter, as in $i = 1. The second part is the test, checked before every run, as in $i -le 3, which means less than or equal to 3. The third part runs after every run, and it usually steps the counter, as in $i++, which adds one. So the order is: set, test, run, step, test, run, step, and so on, until the test fails. In the lesson example, $i starts at 1, prints Try 1, steps to 2, prints Try 2, steps to 3, prints Try 3, steps to 4, and then the test 4 -le 3 fails, so the loop ends. Note that $i ends at 4, the value that failed the test, not at 3, the last value that printed.
The while loop, part by part: a while loop has one test in parentheses, checked before every run, and a block in braces. If the test is false the first time, the block runs zero times, and that is correct behaviour, not an error. If the test is true, the block runs, and then the test is checked again. The body must change something the test depends on, or the test will stay true forever. In the lesson example, the body ends with $count++, which adds one each time, so a test that starts true eventually becomes false. A while loop with no change inside it is not a waiting loop. It is an endless loop, and you will have to stop it by hand.
The do while and do until loops, and why they are different: a do loop checks its test after the block, not before it, so the block always runs at least once. A do while loop repeats while its test is true, just like while, but with the first run guaranteed. A do until loop is the mirror image: it repeats until its test becomes true, which means it keeps running while its test is false. Use a do loop when the block must run first, before there is anything sensible to test, for example when you must ask for a value once before you can check whether it is valid. Do not use a do loop when zero runs is the correct answer, because a do loop cannot give you zero runs.
The foreach loop, part by part: a foreach loop has a loop variable, the word in, and a collection, as in foreach ($server in @("srv1", "srv2")). Before the first run, PowerShell takes the first item and stores it in $server. It runs the block, then it takes the next item, stores it in $server, and runs the block again. When no items are left, the loop ends, and it ends quietly. There is no counter to set, no test to write, and no step to remember, which is why foreach is the clearest loop for lists. You must not add items to, or remove items from, the collection while foreach is running over it, because that can skip items or cause an error. Collect results in a separate list instead.
Collections, arrays, and the range operator: a collection in these examples is often an array, written with @() and items separated by commas, as in @("srv1", "srv2"). The range operator, written as two dots, builds a sequence of numbers for you. So 1..5 means the numbers 1, 2, 3, 4, and 5, in order, and foreach ($n in 1..5) runs five times. A single item is not a list in the same way, and an empty collection, such as @(), simply gives foreach zero runs, with no error and no output. That silence is normal, but it can fool you into thinking the loop ran, when in fact there was nothing to visit.
Think of it like this
Think of it like this: checking a row of lockers. A for loop says check lockers 1 to 10, counting as you go. A while loop says keep checking while the light is on, and stop when it goes off. A foreach loop says check every locker in this row, one by one, and you do not need to count them yourself. A do loop says check at least one locker first, and only then ask whether you should keep going. The locker picture also shows the safety rule: if the light never goes off, or the counter never moves, you will still be checking lockers long after you should have stopped.
How it works, step by step
How it works, step by step: First, choose the loop that matches your job: for when you know the count, while when you do not know how many repeats you need and you are waiting for a change, foreach when you have a list, and do while or do until when the first run must happen before any test makes sense. Second, write the test carefully, and name the step or the change that will end the loop. Third, put the work inside braces, and indent it so the repeated block is easy to see. Fourth, test with a short list or a small count first, such as two items or three runs, so a mistake repeats only a few times, not forever. Fifth, read the output and count the runs, and check that the first run and the last run are the ones you expected.
Loop safety, the most important habit in this lesson: every loop needs a way out that you can see before you run it. For a while loop that waits for something, add a second limit, such as a maximum number of tries, so the loop can end even if the thing you are waiting for never happens. For example, while (($tries -lt 10) -and (-not $done)) keeps looping only while both parts are true, and it stops after ten tries even if $done never becomes true. Test on small data first, never on a full list, because a loop repeats a mistake as faithfully as it repeats correct work. If a loop does run away, press Ctrl and C to stop it, then fix the test or the step before you run it again. Do not just run it again and hope it stops this time.
Break and continue, two small words with opposite jobs: break leaves the whole loop at once, and the script continues with the line after the loop. Continue skips only the rest of the current run, and the loop moves on to its next run, whether that means the next item, the next count, or the next test. So break answers the question should I stop entirely, and continue answers the question should I skip this one and keep going. In a for loop or a foreach loop, continue is safe, because the step or the next item happens automatically. In a while loop, continue is dangerous if it jumps past the line that changes the condition, because then the condition never changes, and the loop never ends. If you use continue in a while loop, change the counter before the continue line, not after it.
Let us walk through the first example, the foreach server check, line by line. The line foreach ($server in @("srv1", "srv2")) says: take the collection with two text items, srv1 and srv2, and visit each one in order. On the first run, $server holds srv1, and the block prints Checking srv1. On the second run, $server holds srv2, and the block prints Checking srv2. There is no third run, because there is no third item. In the output, look for one line per item, in collection order, with the current item in place of $server each time. Change the collection to three servers, and you get three lines, with no other change needed. Change the loop variable name from $server to $name, and you must also change it inside the block, or the block will print an empty or stale value.
Let us walk through the second example, the while count, run by run. The first line sets $count to 0. The while line tests $count -lt 3, where -lt means less than, so the loop runs while the count is below 3. Run one: the test 0 -lt 3 is true, the block prints Count is 0, and $count++ raises $count to 1. Run two: the test 1 -lt 3 is true, the block prints Count is 1, and $count becomes 2. Run three: the test 2 -lt 3 is true, the block prints Count is 2, and $count becomes 3. Run four never happens, because the test 3 -lt 3 is false. In the output, look for three lines, for counts 0, 1, and 2, and notice that there is no line for 3, because the test stops the loop before that run. Remove the $count++ line, and the test would stay true forever, which is the endless loop to avoid.
Let us walk through the third example, the for try count, step by step. The for line has three parts separated by semicolons. The first part sets the counter $i to 1, and it runs once only. The second part tests $i -le 3, where -le means less than or equal to, so the loop runs while $i is 3 or less. The third part, $i++, adds one after each run. So the runs are: test 1 -le 3, print Try 1, step to 2, test 2 -le 3, print Try 2, step to 3, test 3 -le 3, print Try 3, step to 4, test 4 -le 3, which fails, so the loop ends. In the output, look for exactly three lines, numbered 1, 2, and 3. Change -le 3 to -lt 3, and you get only two lines, for 1 and 2, because 3 is no longer included. Change the start to 0, and you get Try 0, Try 1, Try 2, and Try 3, which is four lines, not three, even though the test looks almost the same.
Let us walk through the fourth example, the do while loop that runs at least once. The first line sets $count to 5, which is already past the limit in the test. The do block runs first, before any test, so it prints Run once even though the condition is already false. Only after that run does PowerShell test $count -lt 3. That test is false, so the loop ends after a single run. In the output, look for exactly one line, and notice that this is the point of a do loop: it guarantees a first run. Change $count to 0 at the start, and the same code would print three times, for the same reason a while loop prints three times, because after each run the test is checked again and stays true until $count reaches 3.
Let us walk through the fifth example, the do until loop. The first line sets $tries to 0. The do block runs, adds one to $tries, and prints Try 1. Then PowerShell tests $tries -ge 3, asking whether tries has reached 3. It has not, so the block runs again, printing Try 2, and then again, printing Try 3. After that run, the test $tries -ge 3 is true, so the loop stops, because until means stop when the test becomes true. In the output, look for three lines, numbered 1 to 3. The trap to notice is the wording: do while repeats while the test is true, and do until repeats until the test is true, so the same stopping point needs opposite tests in the two forms. If you write until with a test that is already true, the block still runs once, because the test is only checked after the first run.
Let us walk through the sixth example, the indexed for loop over an array. The first line stores three names in $names. The for line sets $i to 0, tests $i -lt $names.Count, and steps $i by one after each run. The property .Count gives the number of items, which is 3 here, so the test allows $i values 0, 1, and 2. Inside the block, $names[$i] picks the item at position $i, and positions start at 0, not at 1. So run one prints position 0, Ana, run two prints position 1, Ben, and run three prints position 2, Cara. After the third run, $i steps to 3, the test 3 -lt 3 fails, and the loop ends. In the output, look for the position number matching the item: 0 with Ana, 1 with Ben, 2 with Cara. If you wrote -le $names.Count by mistake, the loop would try position 3, which does not exist, and that position would print empty, which is a classic off by one error in indexed loops.
Let us walk through the seventh example, break in a foreach loop. The collection has Ana, Ben, and Cara, in that order. On the first run, $name holds Ana, the if test $name -eq "Ben" is false, so break is skipped, and the block prints Ana. On the second run, $name holds Ben, the if test is true, so break runs, and the whole loop ends at once. Cara is never visited, and nothing after break in that run is printed. In the output, look for only one line, Ana, and notice what is missing: Ben is not printed, because break ran before the print line, and Cara is not printed, because the loop ended. Move the print line above the if test, and Ben would print before break ended the loop, which shows that the order of lines inside a block matters just as much as the order of branches.
Let us walk through the eighth example, continue in a foreach loop over a range. The range 1..5 gives the numbers 1, 2, 3, 4, and 5, in order. On the run for 1, the if test $n -eq 3 is false, so the block prints 1. The same happens for 2. On the run for 3, the if test is true, so continue runs, and the rest of that run, including the print line, is skipped. The loop does not end, though. It moves on to 4, which prints, and then to 5, which prints. In the output, look for 1, 2, 4, and 5, with 3 missing, and notice that the loop still ran five times. Continue skipped one run, it did not shorten the loop or stop it. Change the skipped value from 3 to 5, and the output would be 1, 2, 3, and 4, with only the last run skipped.
When to use it
When to use it, and when not to: use foreach for admin lists, because it is the clearest and the least error prone, and use while when you are waiting for something, such as a step finishing, with a maximum tries limit so the wait cannot last forever. Use for when the count itself matters, such as printing try numbers or walking positions in an array, and use do while or do until when the first run must happen before a test makes sense. Do not use while for a simple list, and do not use for when foreach would say the same thing more clearly. Never run a loop whose body cannot change its own test condition, because that loop will run forever, and you will have to stop it with Ctrl and C.
Nested loops, and why to keep them shallow: a loop can contain another loop, and that is sometimes needed, for example to visit every server and, for each server, visit every service on it. The rule is simple: the inner loop runs to completion for every single run of the outer loop. So if the outer loop has 3 items and the inner loop has 4 items, the inner block runs 12 times in total. That multiplication is why nested loops can surprise you with how much work they do. Keep nesting to two levels when you can, give the outer and inner loop variables different names, such as $server and $service, and test with tiny collections first, so you can count the runs by hand.
Edge cases to check before you trust a loop: an empty collection gives foreach zero runs and no output, which is normal, but it can hide a collection that failed to load, so check the collection size when zero output surprises you. A for loop that steps in the wrong direction, such as starting at 1 and stepping down while testing for less than 10, may run zero times or forever, depending on the start and the test, so read the start, the test, and the step together, never alone. A loop variable keeps a value after the loop ends, so do not assume it is empty afterwards. In the for example, $i is 4 after the loop, because the step ran once more before the final failed test. Finally, all examples in this lesson only print messages. They change nothing on a machine, which makes them safe to practise with, but a loop that runs a changing command will repeat that change once per run, so always test it on a small list first.
Worked examples
Read each example in order. Each one explains its parts, then shows what to look for in the output.
Syntax
foreach ($item in $collection) { <block> }Example 1
Runs once per item, with $server holding the current item each time. First $server is srv1, then it is srv2, then the loop ends, because there is no third item.
foreach ($server in @("srv1", "srv2")) {
Write-Output "Checking $server"
}Illustrative output: Checking srv1 Checking srv2
Example 2
Repeats while the condition holds. The last line changes the counter, so the loop ends. It prints for 0, 1, and 2, and stops before 3, because 3 -lt 3 is false.
$count = 0
while ($count -lt 3) {
Write-Output "Count is $count"
$count++
}Illustrative output: Count is 0 Count is 1 Count is 2
Example 3
A for loop has three parts separated by semicolons. The first part sets the counter $i to 1. The second part tests $i -le 3, where -le means less than or equal to, so the loop runs while $i is 3 or less. The third part, $i++, adds one after each run, so the loop ends after the third run, and the text shows the current try number each time.
for ($i = 1; $i -le 3; $i++) {
Write-Output "Try $i"
}Illustrative output: Try 1 Try 2 Try 3
Example 4
A do while loop runs its block before it tests anything, so it prints once even though $count is already 5 and the test $count -lt 3 is false from the start. After that one run, the test fails and the loop ends.
$count = 5
do {
Write-Output "Run once"
} while ($count -lt 3)Illustrative output: Run once
Example 5
A do until loop repeats until its test becomes true. It prints Try 1, Try 2, and Try 3, and then stops, because $tries -ge 3 is true after the third run. Until is the mirror image of while: it keeps going while the test is false.
$tries = 0
do {
$tries++
Write-Output "Try $tries"
} until ($tries -ge 3)Illustrative output: Try 1 Try 2 Try 3
Example 6
An indexed for loop: positions start at 0, and $names.Count is 3, so $i runs through 0, 1, and 2. Each run prints the position and the name at that position. Using -le instead of -lt here would try position 3, which does not exist.
$names = @("Ana", "Ben", "Cara")
for ($i = 0; $i -lt $names.Count; $i++) {
Write-Output "$i : $($names[$i])"
}Illustrative output: 0 : Ana 1 : Ben 2 : Cara
Example 7
Break leaves the whole loop at once. Ana prints, then Ben matches the if test, so break ends the loop before Ben prints and before Cara is ever visited. The output has only one line.
foreach ($name in @("Ana", "Ben", "Cara")) {
if ($name -eq "Ben") { break }
Write-Output $name
}Illustrative output: Ana
Example 8
Continue skips only the current run. The range 1..5 gives 1, 2, 3, 4, and 5. The run for 3 is skipped, so it does not print, but the loop still goes on to 4 and 5. The output is missing 3, and nothing else.
foreach ($n in 1..5) {
if ($n -eq 3) { continue }
Write-Output $n
}Illustrative output: 1 2 4 5
Nothing on this page executes PowerShell code. The outputs above are illustrative only.
Common mistakes and troubleshooting
Read these before you try the examples, so you can spot the same problems in your own work.
- Writing a while loop whose body never changes the condition, creating an endless loop. Press Ctrl plus C to stop it.
- Using a for loop for a simple list, when foreach would be clearer and less error prone.
- Trying to use a counter called $i inside a foreach loop, expecting it to count items, when foreach has no counter of its own, so $i stays empty or holds an old value from earlier code.
- Mixing up -lt and -le, or stepping in the wrong direction, so a for loop runs one time too many, one time too few, or never ends. Read the start, the test, and the step together, and count the runs by hand for a small case.
- Using continue in a while loop before the line that changes the counter, so the skipped run never changes the condition and the loop never ends. Change the counter before continue, not after it.
- Confusing break with continue: break stops the whole loop, while continue only skips the current run and keeps going. Using break when you meant continue will silently drop every later item.
- Adding items to, or removing items from, a collection while foreach is running over it, which can skip items or cause an error. Build results in a separate list instead.
- Expecting an error from an empty collection, when foreach over an empty collection simply runs zero times and prints nothing. Check the collection size when zero output surprises you.
- Using a do loop when zero runs is the correct answer, and then being surprised that the block ran once anyway. Do loops always run at least once, because they test after the first run.
- Testing a new loop on a full list first, instead of on two or three items. A loop repeats a mistake as faithfully as it repeats correct work, so test small first.
Knowledge check
Knowledge check
Which loop is clearest for processing every item in a list?
Pick one answer. Feedback appears right away, and you can try again.
Remember this and next step
Remember this: for counts, while waits, and foreach visits each item, and do loops always run at least once. Pick the loop that matches the job, make sure it can end, add a maximum tries limit to any waiting loop, and test it small first. Break stops the whole loop, continue skips only the current run, and in a while loop you must change the counter before any continue, or the loop will never end. If you can trace a loop run by run and say how many times it ran and why it stopped, you understand iteration.
Next step: Invoke-Command: run a command remotely