11.4. Looping Constructs

Often in scripts, you want a piece of code to be executed multiple times. You might want it to be executed a specified number of times while a particular condition is true or once for every item in a collection. Windows PowerShell supports looping constructs for each of those situations:

  • for loop — Executes code a specified number of times

  • while loop — Executes code while a specified condition is true

  • foreach loop — Executes code for each item in a collection

Each of the preceding constructs is described in the following sections.

11.4.1. The for Loop

The for statement allows a statement block to be run multiple times, depending on a condition tested before the statement block is run. Whether or not the statement block is executed depends on the result of a conditional test. The for statement takes the following general form:

for ( initialization ; test condition; action)
{
 # a block of statements can go here
}

The following script, ForExample.ps1, shows a simple example using the for statement:

for ($i = 0; $i -lt 10; $i++)
{
write-host "The value of "'$i'" is $i"
}

The variable $i is initialized to 0. The test condition is evaluated. While the value of $i is less than 10, the statement block is executed. Each time the statement block is executed, the value of $i is incremented. The test condition is then evaluated again. If it evaluates to $true, then the statement block is executed again. If it evaluates to $false, then the for loop is completed. Figure ...

Get Professional Windows® PowerShell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.