0
0
PowershellHow-ToBeginner · 3 min read

How to Use Do While Loop in PowerShell: Syntax and Examples

In PowerShell, use the do { ... } while (condition) loop to run a block of code at least once and then repeat it while the condition is true. The code inside do runs first, then the condition is checked after each iteration.
📐

Syntax

The do while loop in PowerShell runs the code block inside do { } first, then checks the while (condition). If the condition is true, it repeats the loop. This ensures the code runs at least once.

  • do { }: The block of code to execute.
  • while (condition): The condition checked after each loop; loop continues if true.
powershell
do {
    # Code to run
} while (condition)
💻

Example

This example shows a do while loop that counts from 1 to 5. It prints the number, then increases it by 1. The loop stops when the number is greater than 5.

powershell
$count = 1
do {
    Write-Output "Count is $count"
    $count++
} while ($count -le 5)
Output
Count is 1 Count is 2 Count is 3 Count is 4 Count is 5
⚠️

Common Pitfalls

Common mistakes when using do while loops in PowerShell include:

  • Forgetting that the loop runs at least once, which can cause unexpected behavior if the condition should prevent any run.
  • Using while instead of do while when you want the code to run at least once.
  • Not updating the variable inside the loop, causing an infinite loop.

Example of a common mistake and fix:

powershell
# Wrong: Infinite loop because $count is not updated
$count = 1
do {
    Write-Output "Count is $count"
} while ($count -le 3)

# Right: Increment $count to avoid infinite loop
$count = 1
do {
    Write-Output "Count is $count"
    $count++
} while ($count -le 3)
Output
Count is 1 Count is 2 Count is 3
📊

Quick Reference

Remember these tips for using do while loops in PowerShell:

  • The loop runs the code block first, then checks the condition.
  • Use do while when you want the code to run at least once.
  • Always update variables inside the loop to avoid infinite loops.
  • Use Write-Output to print inside the loop.

Key Takeaways

Use do { } while (condition) to run code at least once before checking the condition.
Always update loop variables inside the do block to prevent infinite loops.
The condition is checked after the code runs, so the loop runs at least one time.
Use Write-Output to display output inside the loop.
Choose do while over while when you need the code to execute before condition checking.