Introduction
Loops help you repeat tasks easily without writing the same code again and again.
Loops help you repeat tasks easily without writing the same code again and again.
while (<condition>) { # commands to run while condition is true } do { # commands to run at least once } while (<condition>)
The while loop checks the condition before running the code inside.
The do loop runs the code first, then checks the condition to decide if it should run again.
$count is less than 5.$count = 0 while ($count -lt 5) { Write-Output "Count is $count" $count++ }
$count is less than 5 to continue.$count = 0 do { Write-Output "Count is $count" $count++ } while ($count -lt 5)
This script shows how both loops count from 1 to 3 and print the count each time.
$count = 1 Write-Output "Using while loop:" while ($count -le 3) { Write-Output "Count is $count" $count++ } $count = 1 Write-Output "Using do-while loop:" do { Write-Output "Count is $count" $count++ } while ($count -le 3)
Make sure your loop condition will eventually become false, or the loop will run forever.
Use while when you want to check the condition first.
Use do when you want the code to run at least once.
Loops repeat code based on a condition.
while checks condition before running code.
do runs code once before checking condition.
while loop and a do-while loop in PowerShell?while loop behaviorwhile loop checks the condition before running the code inside the loop. If the condition is false initially, the loop body does not run at all.do-while loop behaviordo-while loop runs the code inside the loop once before checking the condition. It then repeats if the condition is true.while checks the condition before running the loop body; do-while runs the loop body once before checking. -> Option Ado-while loop in PowerShell?do-while syntaxdo-while loop syntax is: do { commands } while (condition). The loop runs the commands first, then checks the condition.commands } while (condition) matches the correct syntax exactly. Options C and D have incorrect placement of braces and parentheses. while (condition) { commands } is the syntax for a while loop, not do-while.while and do-while syntax$count = 1
do {
Write-Output $count
$count++
} while ($count -le 3)
do-while loop runs the body first, printing $count starting at 1, then increments $count.while loop code:$i = 5
while ($i -lt 5)
{
Write-Output $i
$i++
}
$i -lt 5 (less than 5). Since 5 is not less than 5, the condition is false initially.while loop body never runs, so no output is produced.do-while loop runs the prompt first, then checks the condition. This fits the need to ask at least once and repeat if needed. A while loop checks condition first, which is not suitable here because input is not available before first prompt.Pass the test and this pattern moves unknown