Back to Basics: The PowerShell For Loop


VPN offers!

1. NordVPN

2. Surfshark

3. ExpressVPN

The PowerShell For Loop is a looping construct which was introduced in PowerShell v3. It has also been available since previous versions, but it wasn’t until version 3 that the syntax of this expression changed significantly and made it more powerful than ever before. This article will cover how to use the for loop with an in-depth look at its three clauses: initialization, condition, and iteration.

The “powershell for loop example” is a simple way to do something in PowerShell. The for loop allows you to iterate through objects, and execute commands on them.

Back to Basics: The PowerShell For Loop

When you utilize PowerShell scripts to administer systems or do large operations, you’ll almost certainly need to employ a loop construct. In PowerShell, there are a variety of loops accessible, one of which is the for loop. The PowerShell for loop command allows you to easily perform the same set of instructions on many things and get consistent results.

In this article, you’ll discover what the for loop in PowerShell is, how to use it, and what a for loop expression looks like. You’ll also pick up on some of the various looping techniques from the examples.

Understanding Loop Statements and Placeholders in PowerShell

When the number of times (iteration count) a command or process needs to execute is already known, the PowerShell for loop is typically utilized. When you just want to handle a subset of the values in an array, for example (e.g., only process 10 of out X number of items).

When you use a for loop, you have greater control over the limitations and criteria that determine when the code should leave. This differs from the foreach loop or the ForEach-Object cmdlet, which stops iterating when the collection’s final item has been handled.

The syntax of the for loop statement is shown below for your convenience.

for (<Initial iterator value>; <Condition>; <Code to repeat>) { <Statement list> }

The PowerShell for loop statement may be split down into four placeholders, as you can see in the syntax above. These are placeholders for the Initial, Condition, Repeat, and Statement lists.

  • You may provide a beginning value in the Initial placeholder. The statement just reads this value once. Scripters usually set the value of this variable to zero.
  • The Condition placeholder sets a limit or condition that will decide whether the loop will continue or terminate. True is the result of the expression used in this placeholder.
  • Multiple instructions may be entered into the Repeat placeholder. After each loop repeats, the instructions in this placeholder are performed before the Condition is re-evaluated. This is often used by scripters to supply an expression to increase or decrease the value in the Initial placeholder.
  • Finally, the primary code that you plan to execute will be inserted in the Statement list placeholder. The code inside this placeholder is looped until the Condition yields a $False value.

Understanding the Loop Execution Flow in PowerShell

You should get acquainted with the PowerShell for loop execution flow to have a better understanding of how it works. A for loop starts off as a four-step process, but after the first run, it becomes a three-step process. Continue reading the algorithm below for more information.


The Initial value is read and placed into memory at the start of the for loop statement.

$num = 0 as an example


The boolean outcome of the equation within the Condition placeholder is evaluated by the for loop statement. The for loop is ended if the result is $false. The for loop moves on to the next step if the result is $true.

$num -lt 10 is an example.


The code is executed by PowerShell within the Statement list placeholder. One or more instructions, script blocks, or functions might be present.

“I count $num,” for example.


The expression in the Repeat placeholder is executed in this phase, and the current value of the Initial placeholder is updated. The flow will then return to Step 2.

$num++ is an example.

Using the For Loop in PowerShell (Examples)

The next sections will show you how to utilize the for loop in a number of situations. These examples may or may not be useful in practice or in real life. However, the skills you’ll learn may help you use for loop if the situation calls for it.

Now that you understand how the for loop works, it’s time to put it all together using simple code.

Obtaining a Number Sequence

Starting at 1, the code below shows the text “I count $num” on the console until the value of $num reaches 10.

“I count $num” for ($num = 1 ; $num -le 10 ; $num++)

This picture displays the effect of copying and pasting the code above into your PowerShell session to execute it.

For example, to show integers fewer than ten in a loopFor example, to show integers fewer than ten in a loop

String Concatenation

The for loop statement may be used with more than only mathematical expressions like addition, subtraction, and multiplication. It may also be used to join two strings together.

The letter “x” will be repeated in the example below, with each line having one more character than the preceding one until the line reaches 30 characters.

As you can see, the value of $x was started with the character “, which has no characters. The condition-based limit is reached when the number of characters in the value of $x hits 30. After each loop, the value of $x is incremented by one letter “x.”

When the code above is performed in PowerShell, the output below reveals the desired outcome.

Using the For Loop to concatenate strings is an example.Using the For Loop to concatenate strings is an example.

String Concatenation with Multiple Initial and Repeat Expressions

Multiple expressions may be used in the Initial and Repeat placeholders in the for loop statement.

Using the code from the previous example, modify it to include a new phrase in the Repeat placeholder to choose a random color. The foreground color of the string to be shown in the console will then be the random color.

An array containing color names is defined in the first line, as you can see. The for loop will choose a color name from this array at random.

There are now two expressions in the Initial and Repeat placeholders. Each phrase is separated by a comma and contained in parentheses.

@colors = $colors (($x=”),($fgcolor = $colors | Get-Random) ;$x.length -le 30;($x=$x+’x’),($fgcolor = $colors | Get-Random)) for (($x=”),($fgcolor = $colors | Get-Random)) Start-Sleep -Milliseconds 20 Write-Host $x -ForegroundColor $fgcolor

The intended outcome of running the changed code in PowerShell is shown below.

Using the For Loop to concatenate strings is an example.Using the For Loop to concatenate strings is an example.

Progress Indicators

The most typical use of the for loop is to provide progress indications. This is often used when doing activities for large quantities of objects that may take a long time to accomplish. For example, preparing a report for all mailbox sizes in your Exchange organization or altering the Active Directory properties of many users.

The example code below demonstrates the most basic method of displaying progress from 1% to 100%. As you can see, the $counter’s starting value is 1, and the condition specifies that the loop will continue until the $counter value reaches 100.

for ($counter = 1; $counter -le 100; $counter++); for ($counter = 1; $counter -le 100; $counter++) # INSERT YOUR CODE HERE -Status “$counter percent Complete:” -PercentComplete $counter; Write-Progress -Activity “Update Progress” -Status “$counter percent Complete:” -PercentComplete $counter;

When you execute the following code in PowerShell, you should get something like this.

The for loop is used to drive the progress counter.The for loop is used to drive the progress counter.

A Countdown Timer is shown on the screen.

The following code demonstrates how to display a countdown timer using the for loop. Starting at 10, this countdown timer just displays the remaining seconds.

You simply need to alter the value of the $seconds variable in the Initial placeholder to change the beginning number.

$seconds -gt -1; $seconds—) for ($seconds=10; $seconds -gt -1; $seconds—) Write-Host -NoNewLine (“‘rseconds remaining: ” + (“0:d4” -f $seconds)) Write-Host -NoNewLine (“‘rseconds remaining: ” + (“0:d4” -f $seconds)) Write-Host -NoNewLine (“‘rseconds remaining: ” 1 – Start-Sleep -Seconds

The example output from running the above code in PowerShell is shown below.

A countdown timer controlled by a for loop.A countdown timer controlled by a for loop.

A Countdown Timer is shown on the screen. (Nested For Loop)

What if you want the countdown timer to be shown in minutes:seconds format? This may be accomplished using a nested for loop. Simply put, a nested for loop is a for loop within another for loop, and so on.

Two for loop statements are included in the example code below.

The first for loop is in charge of the minute component of the timer’s countdown. As you can see, before the for loop, there is a $minutes variable where you must provide the amount of minutes the for loop will countdown from.

The second for loop is in charge of the timer’s seconds countdown. The loop stops for 1 second after each iteration before continuing. It will do it until the value of $seconds approaches zero.

# For ($minutes—; $minutes -gt -1; $minutes—), set the amount of minutes to countdown from $minutes = 1. $seconds -gt -1 ; $seconds—) for ($seconds = 59 ; $seconds -gt -1 ; $seconds—) $remaining = (“0:1” -f (# Set the number of minutes to countdown from $minutes = 1 for ($minutes–; $minutes -gt -1; $minutes–) { for ($seconds = 59 ; $seconds -gt -1 ; $seconds–) { $remaining = (“{0}:{1}” -f (“{0:d4}” -f $minutes),(“{0:d2}” -f $seconds)) Write-Host “`r$remaining” -NoNewline Start-Sleep -Seconds 1 } }:d4″ -f $minutes), (# Set the number of minutes to countdown from $minutes = 1 for ($minutes–; $minutes -gt -1; $minutes–) { for ($seconds = 59 ; $seconds -gt -1 ; $seconds–) { $remaining = (“{0}:{1}” -f (“{0:d4}” -f $minutes),(“{0:d2}” -f $seconds)) Write-Host “`r$remaining” -NoNewline Start-Sleep -Seconds 1 } }:d2″ -f $seconds) Start-Sleep -Seconds 1 Write-Host “‘r$remaining” -NoNewline

When the code above is executed, the countdown timer will appear as seen below.

Using nested for looping, create a countdown timer.Using nested for looping, create a countdown timer.

Choosing a Prime Number

For mathematical computations, PowerShell for loop is also a suitable option. The for loop is used in this example to determine whether a given integer is a prime number.

A prime number is one that can be divided only by one and N, where N is the number itself. For instance, if N is 7, then N divided by 1 is 7 divided by 1.

When the script below is run, it will do the following:

  • Request that the user enter a number.
  • Divide by the dividend, which is the input number, and the divisors are the integers from 2 to the input number minus 1. This indicates that the divisors are 2,3,4,5, and 6, correspondingly, if the input number is 7.
  • The for loop will be halted if the quotient is a whole number, indicating that the input integer is not a prime number.
  • This indicates that the input number is a prime number if the quotient is not a whole number.

This script should be saved as isPrime.ps1.

Read-Host “Input a number” $num = Read-Host “Input a number” for ($y = 2 ; $y -lt $num ; $y++) $isPrime = $true (($num / $y) -is [int]) if (($num / $y) -is [int]) $isPrime = $false break Write-Host “$num is not a prime number” $isPrime -eq $true if ($isPrime -eq $true) “$num is a prime number,” Write-Host says.

To test, execute the isPrime.ps1 script in PowerShell after saving it. See the sample output below for an example.

To find a prime number in a script, use the for loop.To find a prime number in a script, use the for loop.


When compared to how for loop functions in other languages work, the PowerShell for loop has no surprises, which makes it simpler to adapt if you’re not familiar with the notion.

You’ve learnt the fundamentals of the PowerShell for loop statement in this tutorial. You’ve learned about its syntax, logic, and flow, as well as how to utilize it for various reasons from multiple examples.

It’s important to remember that, although there are different loop types in PowerShell, it’s unfair to state that one is superior than the other. It all relies on the code’s purpose and the preferences of the person developing it.

With the information you’ve gained from this post, you should be able to discover new methods to use loop to automate your routine operations.

Additional Reading

The “powershell loop through array of objects” is a basic programming construct in PowerShell. The syntax for the loop is as follows:

=$x++ until ($x<10);"}},{"@type":"Question","name":"Can we use for loop in PowerShell?","acceptedAnswer":{"@type":"Answer","text":"A: Yes, you can use for loop in PowerShell."}},{"@type":"Question","name":"What is PowerShell loop in PowerShell?","acceptedAnswer":{"@type":"Answer","text":"A: A loop is a set of instructions that repeatedly performs the same task."}}]}

Frequently Asked Questions

How does for loop work in PowerShell?

A: For loops are a way to allow for multiple iterations of the same action. In PowerShell, you can use this by using $a = 0;
for($i=1;$i -le 10;$i++) {
} or with $_=$x++ until ($x<10);

Can we use for loop in PowerShell?

A: Yes, you can use for loop in PowerShell.

What is PowerShell loop in PowerShell?

A: A loop is a set of instructions that repeatedly performs the same task.

Related Tags

  • powershell for loop 1 to 10
  • powershell for loop array
  • powershell while loop
  • powershell foreach-object
  • powershell loop until