How to Repeat Commands While a Condition Is True in PowerShell with while
Some tasks repeat until something changes: retry a request, wait for a file, count up to a limit. A while loop runs its block again and again as long as its condition is true. This guide counts three attempts, with real output from PowerShell 7.6.10.
Syntax
while (<condition>) {
<commands>
}
| Part | What it means |
|---|---|
(<condition>) | Checked before each pass. The block runs only while it's true |
{ <commands> } | The commands to repeat. Something in them must change the condition, or the loop never ends |
The about_While page: "The while statement (also known as a while loop) is a language construct for creating a loop that runs commands in a command block as long as a conditional test evaluates to true."
Prerequisites
- PowerShell 7. This guide uses PowerShell 7.6.10.
Step 1: Count Three Attempts
$attempt = 1
while ($attempt -le 3) {
"Attempt $attempt"
$attempt++
}
Attempt 1
Attempt 2
Attempt 3

$attempt -le 3: "less than or equal to 3", checked before each pass.$attempt++: adds 1 each time; after the third pass$attemptis 4, the condition is false, and the loop ends.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Writing <= as in other languages | ParserError: The '<' operator is reserved for future use. | Use PowerShell's comparison operators: -le, -lt, -ge, -gt |
| Forgetting to change the variable in the loop | The condition stays true and the loop never ends | Change it in the block, as $attempt++ does. Ctrl+C stops a runaway loop: an endless while ($true) ended at once |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| The loop body never runs | The condition is false from the start: with $attempt = 5, nothing ran | Check the starting value against the condition |
FAQ
What do -le, -lt, -ge and -gt mean?
Less than or equal, less than, greater than or equal, and greater than. The comparison operators page lists -le as "less than or equal".
How do I leave a loop early?
With break, which ends the loop at once, even while the condition is still true.
Conclusion
while ($attempt -le 3) { ... } ran its block three times and stopped when $attempt reached 4. Use -le and its siblings for comparisons, and change the condition inside the loop.
Additional Resources
- about_While — the while loop.
- about_Comparison_Operators —
-leand the others.
