Powershell Loops - For, While, Do, Until
Some say the definition of insanity is doing the same thing a hundred times and expecting a different result. In PowerShell, insanity when you don't use a loop to do it...
For If you Do Until you fail, Try again While you can!
There are four types of loops in PowerShell: For, While, Do, and Until. Each of these commands work together to loop through a set of commands or scriptblock, until, or while, a condition is met.
In earlier lessons, the If command was used to match a condition before executing a scriptblock. In contrast, loops are used to execute a scriptblock until, or while a condition is met.
A simple example of Do loop is shown below:
Do {
Write-Host "Hello World"
Start-Sleep -Seconds 1
} Until ($false)
In the example, the command Write-Host "Hello World" will be executed until the condition $false is met. Since $false is always false, the command will be executed indefinitely. To break the loop, CTRL+C must be used.
The Until command allows the loop to execute a command until a "if" like condition is met. The command expects a change during the loop. The While command evaluates the condition inside the loop as it is executed. To enforce that concept in PowerShell, the While syntax must be used before the Do command, and the Until syntax must be used after the Do command.
While ($true) {
Do {
Write-Host "Hello World"
Start-Sleep -Seconds 1
}
Until ($false)
}
In this example, while $true is true, the scriptblock will execute the Do command. Since the condition $true is always true, the Do command will execute indefinitely. The until condition, $false (must be false), evaluated at the end of the Do command, will always be false, and the loop will continue to execute indefinitely. Ctrl+C must be used to break the loop.
With these examples, you can now create conditional loops. The next step is to use these commands on a set number of objects.
For Loop
The For command executes a scriptblock, a set number of times. The command expects three parameters: the initialization, the condition, and the increment. The syntax is shown below:
For ($i = 0; $i -lt 10; $i++) {
Write-Host "Hello World"
Start-Sleep -Seconds 1
}
In this example, the For command will execute the Write-Host "Hello World" command 10 times.
The initialization
$i = 0sets the variable$ito 0.The condition
$i -lt 10evaluates the variable$ito be less than 10.The increment
$i++increments the variable$iby 1.The loop will continue to execute until the condition
$i -lt 10is false.
The For initialization variable does not need to be "$i", it can be any variable name, but $i is most commonly used by other PowerShell scripters. ($i is ‘integer’)
What about the ForEach loop?
The For loop's cousin, ForEach, performs the same function as the For loop, but with a set of objects. The syntax is shown below:
$array = @("Hello", "World", "!")
ForEach ($item in $array) {
Write-Host $item
Start-Sleep -Seconds 1
}
In this example, we know the items to iterate through (the $array), and the number of objects inside that array. The ForEach command will execute the Write-Host $item command for each item in the array. The variable $item is used to represent each item in the array. The loop will continue to execute until all items in the array have been processed. Any variable created within the ForEach loop will be destroyed after the loop is completed.
To retain data created inside a For or ForEach loop, a variable (or array) must be created outside the loop. The variable can be used to store data created from inside the loop.
$InputArray = @("Hello","Hello","Hello","Hello","Hello")
$OutputArray = @()
ForEach ($Hello in $InputArray) {
$World = "World"
$HelloWorld = @("$Hello" + " " + "$World" + "`n")
$OutputArray += $HelloWorld
}
Write-Host $OutputArray
In this example, an input array, with five "hello" strings, is created.
An output array, with zero items, is initialized.
The ForEach loop is initiated, using the variable $Hello to represent each item in the input array.
The variable $World is created inside the loop and is used to store the string "World".
The variable $HelloWorld is then created inside the loop.
The $HelloWorld is a concatenation of the string "Hello", then adding a space, adding the string "World", and finally a "`n" notation is used to add a new line to the end of the combined string.
Now $HelloWorld is a combined "Hello World".
The variable $OutputArray, from outside the loop, is used to store the $HelloWorld variable.
The loop will continue to execute all "Hello" items in the input array, until "World" has been added to each one.
Finally, the $OutputArray of five “Hello World” strings is displayed using the Write-Host command.
Back to the For-ture!
The ForEach command is useful when there is an object or list, and the number of objects in the list is known. But what if the command relies on changes to the original list or object? ForEach can create new objects and lists and add those to the original list or object variable, but these are technically "copies" of the original list, with the new item tacked onto the end. The original list or object is not changed. ForEach will be executing on the "old" list or object and will not have the new item or data that was added from inside the loop.
For is the command to use when the commands inside the loop depend on changes happening outside the loop. The For command will execute the scriptblock a set number of times and will evaluate the condition each time the scriptblock loop is executed. The For command is useful when the number of objects in the list is not known, or when the number of objects in the list is expected to change.
$table = @{
String0 = "Hello World 0"
String1 = "Hello World 1"
String2 = "Hello World 3"
}
For ($i = 0; $i -lt $table.count; $i++) {
Do {
$NewString = "Goodbye World $i"
Write-Host $NewString
$Table."string$i" = $NewString
}
Until (
$Table."string$i" -like "Goodbye World*"
)
}In this example, a table is created with three strings.
The For loop is initiated, and the $i variable is used to represent the index of the string in the table.
Do command is executed, and the NEW 0.00%↑ String variable is created inside the loop.
The $NewString variable is used to store the string “Goodbye World” and the number of the indexed item.
Write-Host $NewString command displays the string to the console.
From inside the do loop, the original table value is changed, without creating a new table.
The Until condition checks if the new string was added to the table, if it’s changed correctly, the current loop stops.
The For command increments the loop number and continues until all of the table items are processed.
Summary
The
For,ForEach,While,Do, andUntilcommands are used to create loops.The
Forcommand is used to execute a scriptblock a set number of times, with the ability to change or update the original object.ForEachis a direct loop that iterates through the original objects only, and does not change the original object.While,DoandUntilcommands will execute based on conditions that can change during runtime. This allows for more dynamic control over the flow of the script, adapting to the data being processed.Any code can be used inside the loop, including other loops. This allows for complex scripts to be created, with multiple loops and conditions.

