PowerShell For Loop Explained with Examples

Photo of author

By Victor Ashiedu

Published

Do you want to create a PowerShell loop that runs commands in a command block while a specified condition evaluates to true? Then, you need the PowerShell For loop; this guide teaches you about it and how to use the construct.

Overview

You can use the PowerShell For construct to create a loop that runs commands in a command block while a specified condition evaluates to $true.

The PowerShell For loop is similar to the ForEach loop in that you use both to iterate an array of values. The difference lies in how they interact with the array of values.

While the For loop operates on a subset of an array of values, the ForEach loop iterates all the values in an array.

As you’ll see in the next section, the For construct has an initial (init) value that the command in the block uses to initiate the loop. After running that command, For loop, checks whether the expression in the condition placeholder is $true.

If the condition is $true, the loop performs the repeat operation. An example of a repeat operation in a For loop could be to increment or decrement the initial value.

Finally, the For loop uses the new value from the repeat operation to execute the command in the command block, then the cycle repeats.

Syntax and Parameters of the PowerShell For Loop

The syntax of the PowerShell For Loop construct is represented shown below:

for (<Init>; <Condition>; <Repeat>)
    {
        <Statement list>
    }

The table below is a list of the parameters in the syntax and what they represent.

PowerShell For Loop ParameterNotes
<Init>Use the <init> value to run a command you wish to run before the loop begins.
You usually use the <init> placeholder to define the initial value that the For statement uses to start the execution of the command in the command block of the construct.
<Condition>You place the condition that values to $true or $false in the condition placeholder. The For statement checks this condition. If it returns $true
<Repeat>After the condition in the <Condition> placeholder returns $true, the For loop runs the command in the <Repeat> placeholder. You typically use the <Repeat> placeholder to modify a variable that is tested inside the CONDITION part of the statement.
<Statement list>PowerShell For loop uses this placeholder to run commands that you wish to execute each time the loop repeats.

PowerShell For Loop Examples

So far, I have discussed an overview of the PowerShell For loop construct. You have also learned about its syntaxes and parameters.

In this section, I have discussed several examples and applications of this all-important PowerShell construct.

How To Use PowerShell For Loop To Display 1 To 10

Before I show how to use For loop to display numbers 1 to 10, let me bring back the syntax:

for (<Init>; <Condition>; <Repeat>)
    {
        <Statement list>
    }

To use PowerShell For loop to display 1 to 10, start by assigning an <init> placeholder. In this instance, $a = 1.

You do not have to use the variable, $a. You can use any variable name.

Once you have assigned your init value, the For statement will look like this:

for ($a = 1; <Condition>; <Repeat>)
    {
        <Statement list>
    }

Then, the next step is to add a <condition>. Since we want to count from 1 (the init value) to 10, our condition will be…

$a -le 10

This code will return $true until $a equals 10 – it will stop the loop.

So, with this new code, the For loop code will be updated to look like this…

for ($a = 1; $a -le 10; <Repeat>)
    {
        <Statement list>
    }

Next stop, let’s add a code to the <repeat> placeholder. Since we’re counting from 1 to 10 in incremental values, the <repeat> placeholder will add 1 to $a each time the loop repeats.

Here is the tiny code that does that magic…

$a++

With this new code, our overall PowerShell For loop code will be…

for ($a = 1; $a -le 10; $a++)
    {
        <Statement list>
    }

Finally, it is time to add a code that displays the values from 1 to 10. This time, we add it in the <Statement list> block of the For loop.

Here is the code…

Write-Host $a

And now, our final PowerShell For loop that displays from 1 to 10 is…

for ($a = 1; $a -le 10; $a++)
    {
        Write-Host $a
    }

To see the result, copy the code to a new PowerShell ISE document, select the whole code and click “Run Selection”.

How To Use PowerShell For Loop To Display 1 To 10

How to Increment by 1, 2, or 3 in a For Loop

In the last example, I showed that to increment a For loop by 1; you add $a++ to the <repeat> placeholder of the For loop syntax.

So, how do you increment by 2? I bet you guessed, $a++2.

Well, not quiet. In PowerShell For loop, to increment by 2, you use $a+=2.

By the way, you can also increment by 1 using $a+=1.

So, if we apply this principle to our previous example, the code below will count from 1 to 10 in increments of 2…

for ($a = 1; $a -le 10; $a+=2)
    {
        Write-Host $a
    }

And the result? If you guessed 1,3,5,7 and 9, you’re right!

Based on this, to increment by 3, you use this code…

$a+=3

If we introduced this code to the code that counts from 1 to 10, we would have…

for ($a = 1; $a -le 10; $a+=3)
    {
        Write-Host $a
    }

And the result would be…

How To Increment By, 1, 2 Or 3 In A PowerShell For Loop

How to Use For Loop to Count Down

In the last three examples, I used the For loop to count up in increments of 1 by adding either “++” or “+=1” to the <init> placeholder variable in the <repeat> section.

I want to show you how to do the opposite in this example. Specifically, I want to show you how to count down with the PowerShell For loop.

As you may have guessed, the only thing we need to change is the way we manipulate the <repeat> placeholder. If you did, you will be right!

To count down with For loop, instead of adding “++” or “+=1” to the <init> placeholder variable in the <repeat> section, add “–” or “-=1”.

In the sample code below, I modified the code I used in the second example to count from 10 to 1.

#code that counts downwards from 10 to 1
for ($a = 10; $a -ge 1; $a--)
    {
        Write-Host $a
    }

Here is the previous code to help me explain the difference between the above code that counts down to the previous code that counted up.

#code that counts upwards from 1 to 10
for ($a = 1; $a -le 10; $a++)
    {
        Write-Host $a
    }

Below, I have explained the difference between the two codes:

  1. For the code that counts up, the <init> value starts at 1 ($a = 1). However, for the code that counts down, the <init> value is 10 ($a = 10).
  2. Similarly, I use “$a -le 10” for the <condition> placeholder for the code that counts up. On the contrary, for the code that counts down, I used the opposite code – “$a -ge 1”.
  3. The next difference between the count up and the count down code is the way they handle the <repeat> placeholder of the For loop. While the count-up code defines the <repeat> placeholder as “$a++”, the countdown code defines it as “$a–“

Here is the result in PowerShell ISE for a visual representation of this code.

The “-le” and “-ge” in “$a -le 10” and “$a -ge 1” represents “less than or equal to” and “greater than or equal to” respectively.

How to Use For Loop to Reverse Strings

While I was researching examples to use for this article, I came across this Stack Overflow question – Powershell For Loop In Reverse – Stack Overflow.

The person that posted the question wants to reverse this string – “abcdef” – to this string “fedcba”.

Here is the code that the Stack Overflow member created to achieve this…

$testString = "abcdef"
for ($ia=$testString.length-1; $ia -gt 0; $ia - 2) {
$testString[$ia]
}

Unfortunately, the code does not work. Before you see my close that fixed the problem, can you try to use the knowledge you have gained so far to re-write the code?

Well, here is the code that does the job…

$testString = "abcdef"
$list = 
for ($a=$testString.length-1; $a -ge 0; $a--) {
$testString[$a]
}

$list -join ("")

My code saves the string “abcdef” in a variable called $testString. Then, I created a PowerShell For loop that reverses the string.

However, because I need to use the -join expression to rearrange the result (more on this shortly), I saved the result of the For loop in a variable called $list.

Now, let’s break the For loop code down…

  1. The <init> placeholder “$a=$testString.length-1” checks the length (number of characters) in the string “abcdef”, then subsctracts 1 from the number of characters.

    So, since the number of characters in “abcdef” is 6, the <init> value will start with 5.
  2. Then, the For loop proceeds to the code in the For code block – “$testString[$a]”. This code returns the value of the array defined in the $a variable.

    In this first cycle, it is “$testString[$a]” is “abcdef”[5]. If you run this code, you will see that it displays “f”.
  3. After executing the code in the For code block, the For loop repeats cycle. But, in the second cycle, it runs the code in the <condition> placeholder of the PowerShell For loop.

    The code in the <condition> placeholder is “$a -ge 0”. At this point, $a is “5”, so, it is “greater than” zero (“0).

    Since the <condition> placeholder returns $true, the For loop proceeds to the <repeat> placeholder, which is “$a–“. If you remember in my previous example, I said that a code “$a–” decrements the value in $a by 1.

    Once this is executed, the value of $a becomes “4”.
  4. Next, the For loop proceeds to execute the code in its block section. This time, the code “$testString[$a]” is interpreted as “abcdef”[4].

    Effectively, “abcdef”[4] returns the 4th item in the array, which is “e”.

    At this point, you will have:

    f
    e
  5. The process will repeat again, and at the end, you’ll have:
    f
    e
    d
    c
    b
    a
  6. So, to join the strings and produce “fedcba” – I used the “-join” expression.

Here is the result in PowerShell ISE.

How to Use For Loop to Skip to Next Value

The code below lists numbers from 1 to 10 but skips the number 5

for ($a=1; $a -le 10; $a++)
    {
        If ($a -eq 5) {continue}
        Write-Host $a
   
    }

Here is how it works:

The <init> value of the For loop is 1. This is used in the write-host in the For loop code block.

Within the code, PowerShell checks if the value in the variable $a is equal to 5.

If it is, it continues. That is, it skips the next line – Write-Host $a.

However, if the value in $a is NOT 5, the write-host command writes the value on the console.

Then the For loop repeats the test in the <condition> placehoder, ($a -le 10). If this value returns $true, the loop proceeds to the <repeat> placeholder, ($a++).

The $a++ code instructs PowerShell to increment the value in the variable, $a by 1. Once that is done, PowerShell moves to the code block of the For loop.

Then, the loop repeats until the condition – “$a -le 10” returns $false.

Here is the result of the For script…

How To Use PowerShell For Loop To Skip To Next Value

Frequently Asked Questions

1. How do you loop in PowerShell?

You can loop in PowerShell using the For loop construct. Alternatively, you can loop with the PowerShell ForEach loop statement.

The one you decide to use depends on the items you want to loop or iterate and the commands you want to run.

2. How does loop work in PowerShell?

You use the PowerShell loop to iterate an array of items and run a specific command on each item. How looping works in PowerShell depends on the construct, you use for the looping.

If you use the For construct, it will have an value that runs before the loop begins. Then, at each cycle of the loop, PowerShell tests the command in the placeholder for $true or $false.

If the placeholder executes to $true, PowerShell will proceed to the placeholder. After that, it proceeds to execute the codes in the block.

On the other hand, if you use the ForEach construct, you assign a variable to the subset of arrays you want to loop through. Then, PowerShell uses the first subset value variable to execute the code in the block.

After that, PowerShell returns to the block to check its outcome. Then, depending on the value it returns on the block, it assigns the next value to the sub-set variable – then, uses it to execute the code in the block.

3. What are the different types ofloops in PowerShell?

As I already mentioned in the first two FAQs, PowerShell has the For and the ForeEach loops.

In addition to that, PowerShell also has the Do While, and Do Until loops.

4. What is the difference between ForEach and For loop in PowerShell?

The main difference between the ForEach and For loop in PowerShell is the way the two constructs interact with the array of data they’re looping through.

While the ForEach loop iterates through the array, the For loop iterates through the subset of the data.

In practical terms, the following are the main differences between the ForEach and For loop in PowerShell:

i) The syntax of the For loop is different from that of the ForEach loop
ii) The For loop has an , and placeholders. However, the ForEach loop does not have those placeholders.

5. How do I sleep in PowerShell?

PowerShell has a Start-Sleep cmdlet. You can use this cmdlet to pause (or sleep) a script for a time you specify.

For example, the command – Start-Sleep -Seconds 30 – delays PowerShell for 30 seconds.

Conclusion

The For loop is essential for SysAdmins that write PowerShell scripts. Knowing how it works helps SysAdmins manipulate an array of data and run repeat commands while a condition executes to $true.

Essentially, the For loop have <init>, <condition>, and <repeat> placeholders. You usually use the <init> placeholder to define commands that run before the loop begins.

Then, you use the <condition> placeholder to determine if the loop continues. The loop continues if the <condition> returns $true, otherwise, it stops.

Finally, you use the <repeat> placeholder to assign a value that is used next while PowerShell executes the commands in the <statement list> block.

I hope I made it easy for you to understand the For loop construct and how it works! Kindly take a moment to leave your comments using the “Leave a Reply” form at the bottom of this page.

You could also use the “Was this page helpful?” buttons below to give us your feedback.

Finally, you may find our other PowerShell guides helpful.

We go the extra mile to deliver the highest quality content for our readers. Read our Content Writing, Content Review, and Anti-Plagiarism policies to learn more.

About the Author

Photo of author

Victor Ashiedu

Victor is the founder of InfoPress Media, publishers of Ilifeguides and Itechguides. With 20+ years of experience in IT infrastructure, his expertise spans Windows, Linux, and DevOps. Explore his contributions on Itechguides.com for insightful how-to guides and product reviews.

Related Articles

Get in Touch

If this article does not meet your expectations, kindly let us know. We have various ways you can get in touch with us:

  1. Respond to "Was this page helpful?" above
  2. Leave a comment with the "Leave a Comment" form below
  3. Email us at [email protected] or via the Contact Us page.

Leave a comment

Send this to a friend