Looping Statements
Looping statements in PowerShell allow you to execute groups of statements multiple times.
for Statement
<: loop_label> for(<initialization>; <condition>; <increment>) { <statement block>}
When PowerShell executes a for statement, it first executes the
expression given by <initialization>—for example, $myCounter = 0. It next evaluates <condition>—for example, $myCounter –lt 10. If <condition> evaluates to $true, PowerShell executes the given
statement block. It then executes the expression given by <increment>—for example, $myCounter++. PowerShell continues to
execute the statement block and <increment> statement as long as <condition> evaluates to $true.
The break and continue statements (discussed below) may
specify the loop_label of any enclosing
looping statement as their target.
foreach Statement
<: loop_label> foreach(<variable> in <expression>) { <statement block> }
When PowerShell executes a foreach statement, it executes the pipeline
given by <expression>—for example, Get-Process | Sort Handles or 1..10. For each item produced by the
expression, it assigns that item to the variable specified by <variable> and then executes the given statement
block. For example:
$handleSum = 0;
foreach($process in Get-Process | sort Handles)
{
$SCRIPT:handleSum += $process.Handles
}
$handleSumThe break and continue statements (discussed below) may
specify the loop_label of any enclosing
looping statement as their target.
while Statement
<: loop_label> while(<condition>) { < ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access