Skip to main content

How to Repeat Commands While a Condition Is True in PowerShell with while

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

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​

Syntax
while (<condition>) {
<commands>
}
PartWhat 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​

PowerShell
$attempt = 1
while ($attempt -le 3) {
"Attempt $attempt"
$attempt++
}
Output
Attempt 1
Attempt 2
Attempt 3

PowerShell running the while loop: Attempt 1, Attempt 2 and Attempt 3.

  • $attempt -le 3: "less than or equal to 3", checked before each pass.
  • $attempt++: adds 1 each time; after the third pass $attempt is 4, the condition is false, and the loop ends.

Common Mistakes​

MistakeWhat happensDo this instead
Writing <= as in other languagesParserError: The '<' operator is reserved for future use.Use PowerShell's comparison operators: -le, -lt, -ge, -gt
Forgetting to change the variable in the loopThe condition stays true and the loop never endsChange it in the block, as $attempt++ does. Ctrl+C stops a runaway loop: an endless while ($true) ended at once

Troubleshooting​

SymptomLikely causeFix
The loop body never runsThe condition is false from the start: with $attempt = 5, nothing ranCheck 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​