0
0
PowershellHow-ToBeginner · 3 min read

How to Use While Loop in PowerShell: Syntax and Examples

In PowerShell, use a while loop to repeat a block of code as long as a condition is true. The syntax is while (condition) { commands }, where the commands run repeatedly until the condition becomes false.
📐

Syntax

The while loop runs the code inside its braces repeatedly as long as the condition in parentheses is true.

  • while: keyword to start the loop
  • (condition): a test that must be true to continue looping
  • { commands }: the code block that runs each time the condition is true
powershell
while (<condition>) {
    # commands to run
}
💻

Example

This example counts from 1 to 5 using a while loop. It shows how the loop runs repeatedly while the number is less than or equal to 5.

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

Common Pitfalls

Common mistakes include:

  • Forgetting to update the variable inside the loop, causing an infinite loop.
  • Using a condition that is always true or never changes.
  • Not using parentheses around the condition.

Always ensure the loop condition will eventually become false.

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

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

Quick Reference

ElementDescription
whileStarts the loop
(condition)Runs loop while this is true
{ }Code block to repeat
$variable++Common way to update loop counter

Key Takeaways

Use while (condition) { } to repeat code while the condition is true.
Always update variables inside the loop to avoid infinite loops.
The condition must be inside parentheses and evaluate to true or false.
Use Write-Output to display output inside the loop.
Test your loop with simple conditions before adding complex logic.