PowerShell has verstile scripting language which includes different kinds of loops. The while loop is a common looping syntax found in different langauges.

The basic syntax for a while loop is:

while ( <Condition> )
{
    # Code
}

We can convert from a for loop to a while loop:

# For-loop
for (<Initialization>; <Condition>; <Repeat>)
{
    # Code
}
# While-Loop
<Initialization>
while ( <Condition> )
{
    # Code
    <Repeat>
}

Example: Loop 10 times

$i = 0
while ($i -lt 10)
{
    Write-Output "Loop value = $i"
    $i++
}

ℹ️ We can get the same behavior with a one liner for loop also:

0..9 | ForEach { Write-Ouptut "Loop value = $_" }

ℹ️ If you get stuck in an infinite loop, press Ctrl+C to break out of the loop.

ℹ️ If you want to write a one liner in the PowerShell command line, write the while loop like the following:

while ( <Condition> ) { statement1; statement2; statement3; }

Notice we can put multiple statements on the same line by using ;.

Example: Guess the Number

Given unlimited tries, guess the number from 1 to 10.

$numberToGuess = Get-Random -Minimum 1 -Maximum 10

Write-Output "Guess a number between 1 and 10"

$guess = Read-Host

while ($guess -ne $numberToGuess)
{
    Write-Output "Try again!"

    $guess = Read-Host
}

Write-Output "That's correct! The number was $numberToGuess."