Loops – foreach, do while, do until, while, for
Automation theory tells us that machines are better than people at performing repetitive tasks; they will perform the task any number of times in exactly the same way each time. When we are writing code, we call this iteration or looping. We’re going to look at four examples of looping in PowerShell that are relatively common. We’ll start with the foreach
loop, before looking at do while
and its counterpart, do until
. We’ll then look at the more generalized while
statement and finish with a look at the for
statement and see how it differs from foreach
. Let’s get started by creating a new file, setting it as a PowerShell file, and saving it as loops.ps1
.
The foreach loop statement
This is the most common loop statement. We’ve seen foreach
before, when we looked at the Foreach-Object
cmdlet in Chapter 3, The PowerShell Pipeline – How to String Cmdlets Together. They’re similar...