How to Use PowerShell For Loop, While Loop, and Other Loops – Petri.com

Random topic

close
Windows
Cloud
Microsoft 365
PowerShell
Active Directory
Security
Windows Server
Video
If you are a large enterprise, don’t miss our IT cost-cutting webinar!
Register today!
On-Demand Webinar
MVP Panel Talk: Do You Need to Backup Microsoft 36…
Don’t miss this eBook about M365 Backup!
#1 Microsoft 365 Backup Guide by Veeam
Did you miss our Teams Conference?
GET-IT Microsoft Teams Conference
New E-Book
Tracking Tasks in Microsoft 365
Home
PowerShell
Ivan Mirchev
May 23, 2022
In this article, we will review PowerShell For loops, While loops, Do-While loops, and Do-Until loops. I’ll explain how PowerShell loops are constructed and how to define conditions to enter or exit a loop.
Table of Contents
The For loop is а counting loop, and it’s mostly used when you need to repeat a task a certain number of times, process a collection, or specify items by an index number. It repeats while the test condition evaluates to true and exits on false.
PowerShell For Loop
The syntax for a For loop is the following:
If you would like to repeat a specific operation five times, use the following example:
A PowerShell loop repeating the same operation five times
Here, the variable is initialized with a value of 1, which is less than 5, so you are entering the loop and executing the script block. On each iteration, the value of the variable is incremented by 1 and evaluated against the condition until the result is false.
As the condition is evaluated at the beginning, if the result is false, the command block will not be executed:
If the initial condition if false, the loop won’t be executed
If needed, you may use logical operators to specify more conditions. In this case, we added multiple conditions. And because the logical operator -and results to true only when both conditions are true, the loop stops when the expression $var -ne 3 reaches a false state.
We added another condition to stop the script when the variable reaches a false state.
As stated earlier, you may execute one or more commands in the <Init> and <Repeat> placeholders. In the example below, we have a variable $var1 with an initial value of 1, which increments, and its value is evaluated to test whether it is less than or equal to 5.
However, we also have a second variable, $var2. It has an initial value of 5, which is decremented but not evaluated as part of the condition.
Two different variables are being updated 
In PowerShell, commands are executed sequentially. But sometimes, you may need to repeat a command or a set of commands until a certain condition is met. This is called a loop.
To define what the conditions are to enter or exit a loop in PowerShell, you need to use comparison operators. They will allow you to compare values or find a value that matches a specific pattern. The result is a Boolean value ( true or false), which is evaluated by the loop logic.
You can use comparison operators to compare numeric values:
You can also compare string values with comparison operators:
The Foreach loop is used to iterate through items in a collection. In this scenario, you don’t have a condition to evaluate, but the loop repeats until all items in the collection have been processed.
Here, we start with the foreach statement, followed by brackets with a variable and a collection to iterate. Then comes the script block to be executed. The variable is created automatically and it’s assigned a value from the array prior to each execution of the loop.
Again, to run the loop five times, you will need a collection with five items. In this case, these will be the integer values from 1 to 5:
We ran a PowerShell ForEach loop with a collection of five items.
The variable is initialized with the first value of the collection, which is 1, then the script block is executed. On the next iteration, the variable gets assigned with the next item in the array, which is 2. The script block will be processed again and again until all items in the collection are processed.
For example, if you would like to process the first five services working on your computer, your loop would look like this:
This script shows the first five services working on our computer
You should understand that there is a difference between the Foreach loop and the command Foreach-Object. It’s easy to confuse them. A Foreach loop always starts with a Foreach statement, while the Foreach-Object command will follow a command with a pipeline as it processes the objects sent through it.
The While statement in PowerShell is used to create a loop that runs a command or a set of commands if the condition evaluates to true. It checks the condition before executing the script block. As long as the condition is true, PowerShell will execute the script block until the condition results in false.
Diagram showing how a PowerShell While loop works
The syntax for a while loop is the following:
For example, if you have a variable named var with an initial value of 1 and you would like to repeat the loop five times, the loop should follow this structure:
Example of a loop running five times
In the example above, the variable is initialized outside of the loop and incremented in the script block. The Write-Host cmdlet is used to output the value of the variable on each cycle of the loop.
It is important to note that if the condition is initially false, then the loop will not be triggered. In our example, if we had a value for the variable (var = 6), then the loop command wouldn’t have worked at all and the script block wouldn’t have been executed.
The result of the loop if the initial condition is false
You can use more complex conditions using logical operators. For example, if you would like the variable to be less than 5 and not equal to 3, the loop would look like this:
Running the loop with a variable we want to be less than 5 and not equal to 3
As mentioned earlier, when using the logical operator -and, the result is true only when both conditional tests evaluate to true. In this case, when the variable is assigned the value of 3, the second condition becomes false: This leads to a false result, stopping the loop.
A Do-While loop is a variant of the While loop, and the main difference is that the script block is executed before the condition is checked. This means that even if the start condition is false, the script block will be executed at least once.
Diagram showing how a PowerShell Do-While loop works
The syntax for a Do-While loop is the following:
So, if we use the same example as before, the code would look like this:
Running a Do-While loop
Let’s execute a Do-While loop with a value for the variable var = 6. Here, the loop will still be executed once before checking that the condition was false.
The script was still executed even though the initial condition was false.
Again, using logical operators is also possible. If we use the same example as before, you will see that the loop stops when the value of the variable is 3 because we wanted our variable to be less than 5 and not equal to 3:
The script stops because we wanted our variable to be less than 5 and not equal to 3
The Do-Until loop works in the same way as the Do-While loop: It runs the script block first and then evaluates the condition. The difference here is that while the Do-While loop is entering the loop with a true condition, the Do-Until loop is looking for a false condition to enter the loop.
Diagram showing how a PowerShell Do-Until loop works
The syntax for a Do-Until loop is the following:
As you see, the structure looks almost identical to a Do-While loop. However, let’s see what the result would be if we keep using our previous example:
The Do-Until loop is not triggered as it needs an initial false result
As the conditional test evaluates to true, the Do-Until loop is not triggered because we need a false result to enter the loop. In this case, if you would like to repeat the loop 5 times, the logical operator needs to be changed to greater than (-gt), which will provide a false result for the first 5 iterations:
Changing the logical operator to ‘greater than’ provides us a false result for the first iterations of the loop
Again, as we need the initial condition to be false to enter and stay in the loop, this would affect logical operators as well if we needed to define a more complex expression.
In the following example, we must use the -or operator to have the loop repeat until our variable is greater than 5 (the required false result) or equal to 3. We couldn’t use the -and operator, which would have required the variable to be greater than 5 and equal to 3 at the same time because it would have resulted in an endless loop.
We use the -or operator to have the Do-Until loop repeat until our variable is greater than 5 or equal to 3
You can control the flow of the execution in a loop using keywords to either exit the loop without evaluating the condition or skip the current iteration of the loop. While those keywords can be useful sometimes, they are not always recommended as they can make the script harder to read.
The break statement stops and exits the current loop immediately without executing the rest of the code in the script block of the loop, and without evaluating the specified condition. This allows PowerShell to continue executing the rest of the code.
The break keyword behaves the same regardless of the type of loop used. Using one of the examples from above, we’ll count from 1 to 5 and exit the loop if the counting variable is equal to three. But this time, we’ll add a break instead of using logical operators in the test condition.
To achieve this, the if statement will be used to define the exit criteria.
We’ve used a break statement instead of using logical operators to stop the script
When the value of the counting variable is equal to 3, the if statement is triggered and the break is keyword executed. As the break keyword is placed before the Write-Host command in the script block, the latter won’t be processed. The loop stops and the script continues to execute the remaining code.
The continue statement allows you to skip the remaining part of the code, returning you to the beginning of the loop without exiting it.
As in the previous example, a For loop will be used, but this time instead of exiting the loop when the counting variable reaches 3, PowerShell will skip the remaining code for the current iteration and will proceed with the loop until the conditional test is false.
The if statement is triggered when the value of the variable is equal to 3
As you may have noticed, when the value of the variable is equal to 3, the if statement is triggered, executing the continue statement. It then skips the rest of the code inside the loop without breaking it.
PowerShell supports various types of loops, and it’s really important to understand how they can help you simplify your scripts and repeat certain actions in a consistent way. We’ve covered PowerShell tips and tricks extensively on Petri, so make sure to check out our other guides about how to write PowerShell scripts and how to use the ForEach Parallel option.
Related article:
More from Ivan Mirchev
How to Use a PowerShell Foreach Loop
How to Use the PowerShell Exit Keyword to Terminate Scripts
How to Use PowerShell For Loop, While Loop, and Other Loops
Petri Newsletters
Whether it’s Security or Cloud Computing, we have the know-how for you. Sign up for our newsletters here.
More in PowerShell
Microsoft Releases PowerShell Crescendo 1.1.0-preview01
Dec 8, 2022 | Rabia Noureen
How To Set Environment Variables With PowerShell
Dec 5, 2022 | Sukesh Mudrakola
How to Use a PowerShell Foreach Loop
Oct 24, 2022 | Ivan Mirchev
How to Use a PowerShell Array
Oct 19, 2022 | Michael Reinders
Filtering with PowerShell Where-Object: Easy Examples
Oct 10, 2022 | Michael Reinders
What is PowerShell and How to Get Started With It?
Sep 7, 2022 | Mike Kanakos
Most popular on petri
Article saved!
Access saved content from your profile page. View Saved
Reach out
Learn More
Sitemap

Join The Conversation
Create a free account today to participate in forum conversations, comment on posts and more.
Copyright ©2019 BWW Media Group
Terms and Conditions of Use
Privacy Policy

source

Leave a Reply

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