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"
}
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"
}
This script prints
num = 42
num = 99