PowerShell Genie

PowerShell for / while / do

Three loops cover the remaining cases. while tests the condition before each pass, so a false condition means the body never runs. do { } while ( ) tests afterwards, so the body always runs at least once. do { } until ( ) is the same shape with the condition inverted.

Lesson 2 min read Windows PowerShell 5.1 and PowerShell 7

Documentation: Microsoft Learn

Overview

for ($i = 0; $i -lt 10; $i++) puts initialisation, condition and increment on one line. It is the right choice when you genuinely need a counter, and the wrong choice when you are just walking a collection, where foreach is clearer.

break leaves the loop entirely. continue skips the rest of the current pass and starts the next one. Both work in all of these loops.

Most of the time you do not need any of them. PowerShell's pipeline iterates for you, so reaching for a counter loop to walk an array is usually a sign you have not found the pipeline way to say it yet.

Inspect this example’s structure

Read the command and its supplied arguments. This example requires real PowerShell or its module; this diagram does not execute it.

$i = 1 while ($i -le 3) { $i; $i ++ }
  1. Stage 1$iPositional values or no named parameters

    An example to inspect

    Preview the example. Sign in for the full lesson and activities.

    $i = 1
    while ($i -le 3) { $i; $i ++ }

    What happens

    $i starts at 1. The while condition checks that it is 3 or less, the body outputs the current value, and $i++ increases it. You get 1, 2, 3, and then the condition fails and the loop ends. Remove the $i++ and you have an infinite loop, which is the classic way to write one by accident.

    Worth remembering

    • while tests first. do while and do until test afterwards.
    • for is for real counters. Use foreach to walk a collection.
    • break exits the loop. continue skips to the next pass.
    • Forgetting the increment is how infinite loops happen.

    Primary documentation

    PowerShell objects and pipelines documentation

    Try it

    Illustrative output · values vary by environment

    1PS> $i = 1
    2PS> while ($i -le 3) { $i; $i ++ }

    Example reader

    Inspect this page's example

    Fictional browser data when supported

    Run supported commands against the practice data, or inspect the example without executing it.

    Ready to inspect.

      Counts from 1 to 3 with a while loop.

      Show reference output

      Illustrative output · values vary by environment

      1
      2
      3

      Keep going

      Next: PowerShell Functions
      Genie guidePowerShell for / while / do

      Three loops cover the remaining cases. while tests the condition before each pass, so a false condition means the body never runs. do { } while ( ) tests afterwards, so the body always runs at least once. do { } until ( ) is the same shape with the condition inverted.