In Powershell, one of the features you need to master are loops. There are several types of loops (For, Foreach, Do-While, Until) that you can code, depending on what you need to do with them. In this article, I’m going to introduce you to the different ways of using them and when. First of all, you need to know that these methods work with any version of Powershell and are applicable to almost any programming language. How do you create a loop in Powershell? And when?
The different types of loops in Powershell :
As mentioned in the introduction, there are a number of different methods, each designed to meet a specific need. Do you need a For, Foreach, Do-While or Do-Until loop? Let’s differentiate between them with some examples.
1 – The loop “for” :
This will be used to repeat an instruction a certain number of times. Generally speaking, a variable is used to increment $i++ . Here’s a simple example in which we repeat an instruction 10 times (yes, we start at zero!):
for ($i = 0; $i -lt 10; $i++) {
Write-Host "the count is at $i"
}
2 – The loop “Foreach”
The second is the Powershell Foreach loop, widely used by system administrators. It will help you to browse through a set of values, elements, a given, defined list. Its aim is to go through all the values, right down to the last one. It is often used to browse either an array or a list (such as a list of AD users, for example). Here’s an example with colors :
$colors = "red", "green", "blue", "yellow"
foreach ($color in $colors) {
Write-Host "the color is $colors"
}
3 – The loop “While” or “Do-While”
In Powershell, we use the While loop, as long as a condition is true. It’s quite similar to the Do-While loop. Let’s look at the difference between the two. First of all: While
In our example, the instruction is triggered only if $i is less than 10. In other words, if our starting $i is 11, the code will never be executed.
$i = 0
while ($i -lt 10) {
Write-Host "The counter is at $i"
$i++
}
Conversely, if you use “Do” followed by “While”, the command will be executed at least once, regardless of the starting condition.
$i = 0
do {
Write-Host "The counter is at $i"
$i++
} while ($i -lt 10)
Do you understand the difference?
4 – The loop “Do-Until”
Finally, our last method, again different and for a different purpose, will be used to execute code until a condition is true. In other words, you can quickly make an infinite loop with Powershell. Here’s our last example:
$i = 0
do {
Write-Host "The counter is at$i"
$i++
} until ($i -ge 10)
PowerShell loops are powerful tools which, when mastered, can greatly simplify the automation of repetitive tasks. By understanding the function and use cases of each type of loop, you can write more efficient, effective and elegant scripts. It’s a real time-saver!