PowerShell While and Do-While Loop

The while and do-while loops run a block of code repeatedly based on a condition. Unlike the for loop where the number of iterations is set in advance, these loops continue running as long as a condition remains true — or until something inside the loop changes the outcome.

The while Loop

The while loop checks the condition before each iteration. If the condition is false at the start, the loop body never runs.

  Check Condition
        |
   True? ---> Run Body ---> Check Condition again
        |
   False ---> Stop

Syntax


while (condition) {
    # Code runs as long as condition is True
}

Basic while Loop


$count = 1

while ($count -le 5) {
    Write-Host "Count: $count"
    $count++
}

Output:


Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

while Loop That Never Runs


$value = 100

while ($value -lt 10) {
    Write-Host "This will never print"
}

Write-Host "Loop skipped because condition was false from the start."

Output:


Loop skipped because condition was false from the start.

The do-while Loop

The do-while loop checks the condition after each iteration. This guarantees the loop body runs at least once, even if the condition is false from the beginning.

  Run Body FIRST
        |
  Check Condition
        |
   True? ---> Run Body Again
        |
   False ---> Stop

Syntax


do {
    # Code runs at least once
} while (condition)

Basic do-while Loop


$count = 1

do {
    Write-Host "Count: $count"
    $count++
} while ($count -le 5)

Output:


Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

do-while Always Runs at Least Once


$value = 100

do {
    Write-Host "This prints ONCE even though condition is false."
} while ($value -lt 10)

Output:


This prints ONCE even though condition is false.

while vs do-while – Key Difference

Featurewhile Loopdo-while Loop
Condition checkBefore the loop bodyAfter the loop body
Minimum runs0 (might not run at all)1 (always runs at least once)
Best forWhen the condition might be false immediatelyWhen the body must run at least once (e.g., menus)

The do-until Loop

PowerShell also supports do-until, which runs until the condition becomes true (the opposite of do-while).


# Syntax:
do {
    # runs until condition is True
} until (condition)

$attempts = 0

do {
    $attempts++
    Write-Host "Attempt $attempts"
} until ($attempts -ge 3)

Write-Host "Finished after $attempts attempts."

Output:


Attempt 1
Attempt 2
Attempt 3
Finished after 3 attempts.

Infinite Loop with break

An infinite loop runs forever until something inside it triggers break. Use this for processes that must keep running until a specific condition is met.


$pingTarget = "google.com"

while ($true) {
    $result = Test-Connection -ComputerName $pingTarget -Count 1 -Quiet

    if ($result) {
        Write-Host "$pingTarget is reachable. Exiting loop."
        break
    } else {
        Write-Host "$pingTarget is unreachable. Retrying in 5 seconds..."
        Start-Sleep -Seconds 5
    }
}

while Loop with User Input Validation


$validInput = $false

while (-not $validInput) {
    $age = Read-Host "Enter your age (18-100)"

    if ($age -match "^\d+$" -and [int]$age -ge 18 -and [int]$age -le 100) {
        $validInput = $true
        Write-Host "Age accepted: $age"
    } else {
        Write-Host "Invalid input. Please enter a number between 18 and 100."
    }
}

do-while for Menu Navigation

The do-while loop is perfect for interactive menus because the menu must appear at least once before the user can choose to exit.


do {
    Write-Host ""
    Write-Host "=== Main Menu ==="
    Write-Host "1. List Files"
    Write-Host "2. Check Disk Space"
    Write-Host "3. Show Date and Time"
    Write-Host "0. Exit"

    $choice = Read-Host "Select an option"

    switch ($choice) {
        "1" { Get-ChildItem -Path C:\ | Select-Object -First 10 }
        "2" { Get-PSDrive -Name C | Select-Object Used, Free }
        "3" { Write-Host (Get-Date) }
        "0" { Write-Host "Exiting. Goodbye!" }
        Default { Write-Host "Invalid option. Try again." }
    }

} while ($choice -ne "0")

Accumulation Pattern with while


$total = 0
$count = 0

$numbers = @(10, 25, 33, 47, 62, 78, 90)
$index   = 0

while ($index -lt $numbers.Count) {
    $total += $numbers[$index]
    $count++
    $index++
}

$average = $total / $count
Write-Host "Total: $total"
Write-Host "Count: $count"
Write-Host "Average: $([math]::Round($average, 2))"

Output:


Total: 345
Count: 7
Average: 49.29

Real-World Example – Wait for a Service to Start


$serviceName = "wuauserv"
$maxWait     = 30    # seconds
$elapsed     = 0

Write-Host "Waiting for $serviceName to start..."

do {
    $status = (Get-Service -Name $serviceName).Status
    Write-Host "Status: $status (waited $elapsed seconds)"

    if ($status -eq "Running") {
        Write-Host "$serviceName started successfully."
        break
    }

    Start-Sleep -Seconds 5
    $elapsed += 5

} while ($elapsed -lt $maxWait)

if ($elapsed -ge $maxWait) {
    Write-Host "Timeout: $serviceName did not start within $maxWait seconds."
}

Summary

The while loop checks its condition before running — ideal for situations where the body might not run at all. The do-while and do-until loops check conditions after running — perfect for interactive menus, retry patterns, and scenarios where the body must execute at least once. Infinite loops with break handle continuous monitoring tasks cleanly. These loops combined with break, continue, and Start-Sleep form the core patterns for service watchers, input validators, and menu-driven scripts.

Leave a Comment