Search notes:

PowerShell: while statement

The while statement iterates over a block of statements until a given condition becomes true:
$num = 1

while ($num -lt 6) {
   write-host "$num * $num = $($num*$num)"
   $num++
}
#
# 1 * 1 = 1
# 2 * 2 = 4
# 3 * 3 = 9
# 4 * 4 = 16
# 5 * 5 = 25
Github repository about-powershell, path: /language/statement/while/condition.ps1

Assignment

It is possible to assign a value to a variable in the while loop's condition. After assigning a value to the variable, the value of the variable is checked in a boolean context.
This is demonstrated in the following example:
$nums  = 42, 99, 17, 0, 12

$index = -1
function nextNum() {
   $script:index ++
   return $script:nums[$script:index]
}

while ($num = nextNum) {
   write-host "num = $num"
}
Github repository about-powershell, path: /language/statement/while/assignment.ps1
Because 0 is considered to be $false in a boolean context, the loop terminates when nextNum() returns 0. Thus, this script prints
num = 42
num = 99
num = 17
It is also possible to assign a value and check the assigned value with a comparison operator. Because the assignment has a lower precedence than the comparison operator, the assignment must be put into parentheses:
$nums  = 42, 99, 17, 0, 12

$index = -1
function nextNum() {
   $script:index ++
   return $script:nums[$script:index]
}

while ( ($num = nextNum) -gt 22) {
   write-host "num = $num"
}

Github repository about-powershell, path: /language/statement/while/assignment-gt.ps1
This script prints
num = 42
num = 99

See also

Other statements

Index