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

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/Windows/...', 1740464689, '18.189.30.193', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/Windows/PowerShell/language/statement/while/index(93): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78