🎓 A1Learner
🔍
0 of 52 lessons completed

PowerShell For Loop

A for loop is a loop that repeats its block while a counter meets a test. You set the start, the test, and the step in one line.

Count up from zero

The counter $i starts at 0 and stops before 3.

for ($i = 0; $i -lt 3; $i++) { $i }

Count with a message

The block can use the counter in a printed message.

for ($i = 1; $i -le 3; $i++) { "Count $i" }

Step by two

The step does not have to be one. Here it adds two each pass.

for ($i = 0; $i -le 6; $i = $i + 2) { $i }

Example

for ($i = 3; $i -ge 1; $i--) { "T-minus $i" }
"Liftoff"

Key points

  • Counter: a variable that holds the current count, and changes on each pass.
  • Start: the first part sets the counter to its starting value.
  • Test: the loop keeps running while the test is true, and stops when it is false.
  • Step: the last part changes the counter after each pass, often by one.
  • Use a for loop when you know how many times to repeat a job.

In this example, $i starts at 3 and falls by one after each pass. The loop prints a countdown line for 3, 2, and 1, then stops. The last line prints Liftoff after the loop ends.

Note

PowerShell uses $i++ to add one to $i, and $i-- to subtract one.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does this loop print? for ($i = 0; $i -lt 3; $i++) { $i * 2 }