On this page

Loops

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

Loops allow a script to repeat an action multiple times. Each loop type has a specific purpose and syntax. This section explains how each loop works, how the syntax is structured, and provides examples that students can run directly on their machines.


1. for Loop​

The for loop is used when you know exactly how many times you want to repeat something.

Its syntax mirrors C‑style loops:


for (<initialization>; <condition>; <iteration>) {

    <code>

}

Example: counting from 1 to 5​


for ($i = 1; $i -le 5; $i++) {

    "Iteration: $i"

}

Explanation:


Iteration: 1

Iteration: 2

Iteration: 3

Iteration: 4

Iteration: 5

Example: summing numbers​


$sum = 0



for ($i = 1; $i -le 5; $i++) {

    $sum += $i

}



$sum

This calculates 1 + 2 + 3 + 4 + 5 and prints 15.


2. foreach Loop​

foreach is used to iterate through each element in a collection (arrays, lists, command output).

Syntax:


foreach (<item> in <collection>) {

    <code>

}

Example: iterating through an array​


$colors = "red", "green", "blue"



foreach ($color in $colors) {

    "Color: $color"

}

Explanation:

Example: processing files​


$files = Get-ChildItem



foreach ($file in $files) {

    $file.Name

}

Explanation:


3. while Loop​

while repeats as long as a condition remains true.

Syntax:


while (<condition>) {

    <code>

}

The condition is checked before each iteration.

Example: count down from 5​


$i = 5



while ($i -gt 0) {

    "Countdown: $i"

    $i--

}

Explanation:

Example: waiting for a condition​


$number = 0



while ($number -lt 3) {

    "Number is $number"

    $number++

}

This prints:


Number is 0

Number is 1

Number is 2

4. do Loop​

A do loop always runs at least once, because the condition is checked after the loop body.

There are two forms:


4.1 do … while​

Runs the block, then repeats while the condition is true.

Example​


$i = 1



do {

    "Value: $i"

    $i++

} while ($i -le 3)

Explanation:


4.2 do … until​

Runs the block until the condition becomes true.

Example​


$i = 1



do {

    "Value: $i"

    $i++

} until ($i -gt 3)

Explanation:


5. Choosing the Right Loop​

Loop TypeUse WhenforYou know the exact number of iterationsforeachYou want to process each item in a collectionwhileYou want to repeat until a condition changesdo … while / untilYou need the loop to run at least once

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

If Switch

Next

Script Blocks and Scoping Rules