How to Use PowerShell For Loop, While Loop, and Other Loops

Last Update: Mar 13, 2024 | Published: May 23, 2022

PowerShell

SHARE ARTICLE

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.

PowerShell For loop

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.

Diagram showing how a For loop works
PowerShell For Loop

The syntax for a For loop is the following:

for (<Init>; <Condition>; <Repeat>) {

<Script Block>

}
  • The <Init> block executes a command or a set of commands before the loop begins. Usually, this is the place where you initialize the counting variable.
  • In the <Condition> section, you evaluate the conditional test. If it’s true, you are entering the loop and executing the commands in the script block. Then, the condition is evaluated again until it results in false.
  • The <Repeat> placeholder executes one or more commands, separated by commas on each loop iteration. Usually, it is used to modify the counting variable.

If you would like to repeat a specific operation five times, use the following example:

for ($var = 1; $var -le 5; $var++) {

Write-Host The value of Var is: $var

}

Write-Host End of for loop.
We used a for loop to repeat an operation five times
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:

for ($var = 6; $var -le 5; $var++) {

Write-Host The value of Var is: $var

}

Write-Host End of for loop.
If the initial condition if false, the loop won't 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.

for ($var = 1; $var -le 5 -and $var -ne 3; $var++) {

Write-Host The value of Var is: $var

}

Write-Host End of for loop.
We added another condition to stop the script when the variable 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.

for (($var1 = 1), ($var2 = 5); $var1 -le 5; ($var1++), ($var2--)) {

Write-Host The value of Var1 is: $var1

Write-Host The value of Var2 is: $var2

}

Write-Host End of for loop.
Two different variables are being updated
Two different variables are being updated 

How to define PowerShell loop conditions

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:

Operation Result
2 -eq 2 True
2 -eq 5 False
3 -gt 7 True
5 -lt 3 False

You can also compare string values with comparison operators:

Operation Result
‘PowerShell’ -eq ‘powershell’ True
‘PowerShell’ -eq ‘cmd’ False
‘PowerShell’ -like ‘power*’ True
‘PowerShell’ -notlike ‘*shell’ False

PowerShell Foreach loop

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.

<Figure Foreach_Diagram.png>

The syntax for a Foreach loop is the following:

foreach ($<item> in $<collection) {

<Script Block>

}

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:

$collection = 1..5

foreach ($item in $collection) {

Write-Host The value of Item is: $item

}

Write-Host End of foreach loop
We run a foreach loop with a collection of five items.
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:

foreach ($service in (Get-Service | Select-Object -First 5)) {

Write-Host Service name is: $service.name and status is $service.status

}
This script shows the first five services working on our computer
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.

PowerShell While loop

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 While loop works
Diagram showing how a PowerShell While loop works

The syntax for a while loop is the following:

while (<Condition>){<Script Block>}

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:

$var = 1

while ($var -le 5)

{

Write-Host The value of Var is: $var

$var++

}

Write-Host End of While loop.
Example of a loop running five times
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.

$var = 6

while ($var -le 5)

{

Write-Host The value of Var is: $var

$var++

}

Write-Host End of While loop.
The result of the loop if the initial condition is false
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:

$var = 1

while ($var -le 5 -and $var -ne 3)

{

Write-Host The value of Var is: $var

$var++

}

Write-Host End of While loop.
Running the loop with a variable we want to be less than 5 and not equal to 3
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.

PowerShell Do-While 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 Do-While loop works
Diagram showing how a PowerShell Do-While loop works

The syntax for a Do-While loop is the following:

do {

<script block>

} while (<condition>)

So, if we use the same example as before, the code would look like this:

$var = 1

do {

Write-Host The value of Var is: $var

$var++

} while ($var -le 5)

Write-Host End of Do-While loop.
Running a Do-While loop
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.

$var = 6

do {

Write-Host The value of Var is: $var

$var++

} while ($var -le 5)

Write-Host End of Do-While loop.
The script was still executed even though the initial 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:

$var = 1

do {

Write-Host The value of Var is: $var

$var++

} while ($var -le 5 -and $var -ne 3)

Write-Host End of Do-While loop.
The script stops 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

PowerShell Do-Until loop

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 Do-Until loop works
Diagram showing how a PowerShell Do-Until loop works

The syntax for a Do-Until loop is the following:

do {

<script block>

} until (<condition>)

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:

$var = 1

do {

Write-Host The value of Var is: $var

$var++

} until ($var -le 5)

Write-Host End of Do-Until loop.
The Do-Until loop is not triggered as it needs an initial false result
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:

$var = 1

do {

Write-Host The value of Var is: $var

$var++

} until ($var -gt 5)

Write-Host End of Do-Until loop.
Changing the logical operator to 'greater than' provides us a false result for the first iterations of the loop
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.

$var = 1

do {

Write-Host The value of Var is: $var

$var++

} until ($var -gt 5 -or $var -eq 3)

Write-Host End of Do-Until loop.
We use the -or operator to have the Do-Until loop repeat until our variable is greater than 5 or equal to 3
We use the -or operator to have the Do-Until loop repeat until our variable is greater than 5 or equal to 3

How to control PowerShell loops

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

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.

For ($var = 1; $var -le 5; $var++) {

if ($var -eq 3) {break}

Write-Host The value of Var is: $var

}

Write-Host End of for loop.
We've used a break statement instead of using logical operators to stop the script
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

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.

for ($var = 1; $var -le 5; $var++) {

if ($var -eq 3) {Continue}

Write-Host The value of Var is: $var

}

Write-Host End of for loop.
The if statement is triggered when the value of the variable is equal to 3
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.

Conclusion

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:

SHARE ARTICLE