0
0
PowerShellscripting~5 mins

While and Do-While loops in PowerShell

Choose your learning style9 modes available
Introduction

Loops help you repeat tasks easily without writing the same code again and again.

When you want to keep asking a user for input until they give a valid answer.
When you need to process items in a list one by one until none are left.
When you want to run a task repeatedly until a certain condition changes.
When you want to check a condition before or after running some code multiple times.
Syntax
PowerShell
while (<condition>) {
    # commands to run while condition is true
}

do {
    # commands to run at least once
} while (<condition>)

The while loop checks the condition before running the code inside.

The do loop runs the code first, then checks the condition to decide if it should run again.

Examples
This loop runs as long as $count is less than 5.
PowerShell
$count = 0
while ($count -lt 5) {
    Write-Output "Count is $count"
    $count++
}
This loop runs the code first, then checks if $count is less than 5 to continue.
PowerShell
$count = 0
do {
    Write-Output "Count is $count"
    $count++
} while ($count -lt 5)
Sample Program

This script shows how both loops count from 1 to 3 and print the count each time.

PowerShell
$count = 1
Write-Output "Using while loop:"
while ($count -le 3) {
    Write-Output "Count is $count"
    $count++
}

$count = 1
Write-Output "Using do-while loop:"
do {
    Write-Output "Count is $count"
    $count++
} while ($count -le 3)
OutputSuccess
Important Notes

Make sure your loop condition will eventually become false, or the loop will run forever.

Use while when you want to check the condition first.

Use do when you want the code to run at least once.

Summary

Loops repeat code based on a condition.

while checks condition before running code.

do runs code once before checking condition.