In this PowerShell tutorial we show you how to use the For loop, ForEach-Object loop, and the While, Do-While and Do-Until loops.
There are several types of loops available in PowerShell, and in many cases more than one loop technique can be used effectively. At times determining the most efficient loop type is required, either from a performance or code readability perspective.
ForEach-Object Loop
In many cases using the ForEach-Object cmdlet (previously discussed in our article on working with PowerShell objects) is the best way to loop through an object. At it's most simple, ForEach-Object requires only an object to be looped through and a script block containing the commands to be performed on each member of the object.
These parameters can be specified either by the -InputObject and -Process parameter names, or by piping the object to the ForEach-Object cmdlet and placing the script block as the first parameter. To illustrate this basic syntax the following example shows two methods of using ForEach-Object to loop through the contents of a user's Documents folder:
$myDocuments = Get-ChildItem $env:USERPROFILEDocuments -File
$myDocuments | ForEach-Object {$_.FullName}
ForEach-Object -InputObject $myDocuments -Process {$_.FullName}
In certain scenarios it may be beneficial to perform one or more actions just before or just after the loop is performed. The -Begin and -End parameters can be used to define script blocks to execute just before or after the contents of the -Process script block. This can be used to set or modify a variable before or after execution of the loop.
ForEach-Object has two aliases, ForEach and %, and also supports shorthand syntax beginning in PowerShell 3.0. The following three examples are identical in function.
Get-WMIObject Win32_LogicalDisk | ForEach-Object {$_.FreeSpace}
Get-WMIObject Win32_LogicalDisk | ForEach {$_.FreeSpace}
Get-WMIObject Win32_LogicalDisk | % FreeSpace
PowerShell For Loop
For loops are typically used to iterate through a set of commands a specified number of times, either to step through an array or object, or just to repeat the same block of code as needed. A For loop is constructed by setting the value of a variable when entering the loop, the condition on which the loop should be terminated, and an action to be performed against that variable each time through the loop.
The following example shows a basic For loop used to create a multiplication table:
For ($i=0; $i -le 10; $i++) {
"10 * $i = " + (10 * $i)
}
For loops can be used to step through array values by setting the initial value to the initial index of the array and incrementally increasing the value until the array length is met. The array index is specified by placing the incremented variable inside square brackets immediately following the variable name, as shown in the following example:
$colors = @("Red","Orange","Yellow","Green","Blue","Indigo","Violet")
For ($i=0; $i -lt $colors.Length; $i++) {
$colors[$i]
}
While, Do-While, and Do-Until Loops
A third type of loop that PowerShell supports involves setting a condition which either allows the loop to process as long as the condition is true or until it is met. While and Do-While loops are both used to perform an action while the condition evaluates to $true, and differ only in their syntax. Do-Until loops have similar syntax to Do-While, but stop processing once the condition statement is met.
Do-While and Do-Until loops both begin with the Do keyword prefacing a script block, followed by the condition keyword (While or Until) and the condition. As an example the following two loops function identically, only the condition is reversed:
$i=1
Do {
$i
$i++
}
While ($i -le 10)$i=1
Do {
$i
$i++
}
Until ($i -gt 10)
While loops perform identically to Do-While loops, only the syntax is altered slightly. While loops use only the While keyword, followed by the condition, and finally the script block. This loop is identical in function to the preceding examples, and uses the same condition as the Do-While loop:
$i=1
While ($i -le 10)
{
$i
$i++
}
Any of these three loop types -- Do-While, Do-Until, and While loops -- can also be used to loop indefinitely; While and Do-While loops with the condition set to $true and Do-Until with the condition set to $false.
In some situations you may need to exit a loop early based on something other than the loops condition. In this case the Break keyword can be invoked in order to exit out of the loop. This final example shows the same functionality, but uses an infinite loop and the Break keyword to exit out at the appropriate time:
$i=1
While ($true)
{
$i
$i++
if ($i -gt 10) {
Break
}
}