PowerShell Loops

In PowerShell scripting there are several types of loops. This page will explain what a loop is, the different types and how to know what loop to use for a particular task. So a loop just runs code over and over in a loop until some condition is met. One condition could mean that there are no more things to process or continue to run until a particular key is pressed. For example, you wanted to ping 50 servers, or you have 50 IPv4 addresses, and you need to run nslookup on each one. This is where a loops come in. If you’re a person who runs commands over and over, those days are over!

There are several different loop types:

  • For
  • Foreach
  • While
  • Do While (runs while condition is true)
  • Do Until (runs while condition is false)

For Loop

I typically don’t use for loops often at all. For loops are used if you need to run something a certain number of times. Let’s say you want to print the famous “hello world!” 5 times to the screen.

for($i=0;$i -le 5; $i++){
    Write-Output "Hello World!!!"
}

Hello World!!!
Hello World!!!
Hello World!!!
Hello World!!!
Hello World!!!

Let explain the above code now. First we call the for loop by typing for() with parentheses. Inside the parentheses is the following (<int>;<condition;<addition>). So for our example we set the $i variable to zero 0. next we check is $i less than or equal to 5? Then we increment $i by 1 (note: this could be done in the for loop script block). Then in the script block we state to write “Hello World!!!” to the screen.

Foreach Loop

I’m a huge fan and big user of Foreach loops. This is my daily goto. So lets say you have a list of object(s). For example Names “Matt”,”Bob”,”Alice”. So this loop would run foreach object in this case the objects are names. So based on these names this loop would run 3 times. Now in those 3 runs you can do anything you want. For example we’ll say Hi to each person.

# Make an Array of names 
$employees = "Matt","Bob","Alice"

Foreach($person in $employees){
    Write-Output "Hi $person!"
}

Hi, Matt!
Hi, Bob!
Hi, Alice!

Now I’m sure you’re wondering where did $Person come from? This can be any name it’s a variable that is created and updated on the fly for each person. So first $Person is Matt then it executes the code in the script braces { }. Next $person becomes Bob and executes the code in the script braces { }. Lastly, it updates $person with Alice and executes the code. Now that there are no more objects the loop is complete.

We can take this 1 step further and add an example with a little more logic using if statements. So if the name is Bob then he’s fired.

# Make an Array of names 
$employees = "Matt","Bob","Alice"

Foreach($person in $employees){
    if($person -eq "Bob"){
        Write-Output "Hi $person, I'm sorry be you're fired!"
    }else{
        Write-Output "HI $person!"
    }
}

HI Matt!
Hi Bob, I'm sorry be you're fired!
HI Alice!

The main thing to capture is foreach loops means you know the end. You know how many objects you’re going to do something for. Have a 100 users this will run 100 times easy.

While

Now while loops are useful when you don’t know the end. You have no idea how many times something should run for. I know this sounds crazy at first but let me try to give some good examples.

One example would be a web browser. Your browser you’re reading this post on is probably running in a while loop. Each time it runs through it looks for any Clicks or key presses. Did they click the X to close? Yea? Well I’m finally done lets get out this loop.

Another good example is if you’re executing tons of commands and use jobs in PowerShell. You don’t know how many jobs are going to create and complete successfully. So you can say while I’m still created jobs and pulling data run.

While loops will run while a condition is true. You have to be very careful you don’t get into an infinite loop this is bad haha. so don’t do While $True because $True will never change to $False. Lets jump into some code and examples!

$run = $true
while($run){
    $answer = Read-Host -Prompt "Press q to quit"
    if($answer -eq "q"){
        $run = $false
    }
}

The above loop will continue to run until the user inputs “q” to quit.

Do While

Do While loops are similar to a While loop. The only difference here is the Do runs first before checking the condition of the while loop. If that condition is still true then the DO runs again until the condition in the while is $false.

$run = $true
do {
    $answer = Read-Host -Prompt "Press q to quit"
    if($answer -eq "q"){
            $run = $false
    }
}while ($run)

Do Until

Lastly, Do Until acts like Do while except the syntax is a little different and the conditions runs while it’s $False instead of $True. Lets use the same code from Do While but flip our $run values.

$run = $false
do {
    $answer = Read-Host -Prompt "Press q to quit"
    if($answer -eq "q"){
            $run = $true
    }
}until ($run)

Leave a Reply

Your email address will not be published. Required fields are marked *

Close Bitnami banner
Bitnami