Home PowerShell 11 Examples of How to Use PowerShell For Loops

# 11 Examples of How to Use PowerShell For Loops

When you utilize PowerShell scripts to administer systems or do mass activities, you’ll almost certainly need to employ a loop construct. In PowerShell, there are a variety of loops accessible, one of which is the PowerShell For loop.

The PowerShell for loop command allows you to rapidly execute the same set of instructions on numerous objects and get consistent results.

In this article, I would be showing you all you need to know about the PowerShell For loop, how to use it, and how to write it. I will also show you some of the different techniques I like to apply when writing For loops.

Heads up, this is not a very complicated statement to write, and once you get the basic syntax, you would be able to play around with different variations.

What Will I Learn?💁

### What is The PowerShell For Loop Statement and What Are Its Placeholders

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

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

The structure of the for loop statement is shown below for your convenience:

for (<Initial value for iteration>; <Condition>; <Code meant to be repeated>)
{
<Statement list>
}

The PowerShell for loop statement may be split down into four placeholders, as shown in the syntax above. These are placeholders for the Initial value, the condition, a repeat code, and Statement list or lists.

1. 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.
2. The Condition placeholder provides 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.
3. Multiple instructions may be entered into the Repeat placeholder. After a loop has been repeated, the set of instructions in this placeholder are carried out and then the condition gets re-evaluated. Severally this method is used by scripters to get an expression to either increase or decrease the value in the Initial placeholder.
4. Finally, the primary code that you want to execute will be put in the Statement list placeholder. The code placed here is looped until the Condition yields a $False value. ### How Are PowerShell For Loops Executed? 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. Keep reading the methodology below for more explanation. STEP ONE The Initial or the starting value is read and put into memory at the start of the for loop statement. For instance: $num = 1

STEP TWO

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

For instance:

$num -lt 11 STEP THREE The code is executed by PowerShell within the Statement list placeholder. One or more instructions, functions, or script blocks may be present. For instance: I count$num

STEP FOUR

The statement in the Repeat placeholder is executed in this phase, and the present value of the first placeholder is updated. The flow of execution will then return to the second step.

For instance:

$num++ ## Examples of How to Use PowerShell For Loops Now I will show you how to utilize the for loop in a number of situations. These examples may not always be useful in practice or in real life. However, the methods you’ll learn may help you use for loop if the situation calls for it. At this point, I believe you know how Powershell Loops wor, so let us try some simple code. ### 1. Using Powershell For Loops to Get Sequence of Numbers Starting at 5, the code below shows the text “I count$num” on the console until the value of $num reaches 15. for ($num = 5 ; $num -le 15 ;$num++){ "I count $num"} ### 2. Using Powershell For Loops to Concatenate Strings The for loop statement may be used with more than only mathematical expressions such as subtraction, addition, and multiplication. It may also be used in joining two strings together. The letter “o” will be repeated in the example below, with each line having one more character than the preceding one until the line reaches 25 characters. As is depicted, the value of$o was started with the character ‘ ‘, which has no characters. The condition-based limit is reached when the number of characters in the value of $o exceeds 25. After each repetition, the value of$o is incremented by one letter “o.”

for ($o='' ;$o.length -le 25;$o=$o+'o'){
Write-Host $o Start-Sleep -Milliseconds 20 } When the script above is executed in PowerShell, the output below displays the anticipated outcome. ### 3. Using Powershell For Loops to Concatenate Strings With Repeat Expressions & Multiple Initials Multiple expressions may be used in the Initial (First) and Repeat placeholders in a for loop statement. Using the code from the previous example, modify it to include a new phrase in the Repeat placeholder that chooses 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 the name of a color 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 = @("Cyan","Green","Red","Yellow","Magenta","White")
for (($a=''),($fgcolor = $colors | Get-Random) ;$a.length -le 25;($a=$a+'o'),($fgcolor =$colors | Get-Random)){
Write-Host $a -ForegroundColor$fgcolor
Start-Sleep -Milliseconds 20
}

The output should be similar to the diagram below:

### 4. Using Powershell For Loops to Display Progress

The most frequent use of the for loop is to provide progress indications. This is often used when doing activities for large quantities of things that may take a long time to finish. Take for instance, working on the Active Directory for many users or even generating reports on an Exchange server.

The example code below demonstrates the most basic method of displaying progress from percent to 100 percent. 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++ ) { # YOUR CODE GOES HERE Write-Progress -Activity "Progress Update" -Status "$counter% Done:" -PercentComplete $counter; }  Below is a sample result to expect: ### 5. Using Powershell For Loops to Display a Countdown Timer The following code demonstrates how to generate a countdown timer using the for loop. Starting at 15, this countdown timer simply displays the remaining seconds. You just need to modify the value of$seconds parameter in the Initial placeholder to change the beginning number.

for ($seconds=15;$seconds -gt -1; $seconds--) { Write-Host -NoNewLine ("Seconds left: " + ("{0:d4}" -f$seconds))
Start-Sleep -Seconds 1
}

The expected result should be the following:

### 6. Using Powershell Nested For Loop to Display a Countdown Timer

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

Here are 2 For loop statements example codes below.

The first for loop takes care of the minute part of your timer’s countdown. As you can see, before the for loop, there is a $minutes variable where you must provide the number of minutes the for loop will countdown from. The second Powershell for loop takes care 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.

### 7. Using Powershell For Loops to Determine a Prime Number

For mathematical calculations, For loop is also an excellent option. The Powershell for loop is used in this scenario to evaluate whether or not a given integer is a prime number.

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

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

• Request that the user enters a number.
• Divide by the dividend (the dividend being the input number), and the numbers dividing are the integers from 2 down to minus 1 of the input number. This simply means that the divisors, in this case, would be 2,3,4,5, and 6, if the number that was input is 7.
• The “For loop” will be stop execution when the product is a whole number. This shows that that the input integer is not a prime number.
• Contrastingly, the input number is a prime number if the quotient is not a whole number.
• This script should be saved as ourPrime.ps1.
$num = Read-Host "Type in a number"$ourPrime = $true for ($x = 2 ; $x -lt$num ; $x++ ) { if (($num / $x) -is [int]) { Write-Host "$num inputed isn't prime number"
$ourPrime =$false
break
}
}

if ($isPrime -eq$true) {
Write-Host "$num inputed is a prime number" } ### 📗FAQ📗 #### How to do a for loop in PowerShell? To create a for loop in PowerShell, you can use the following syntax: for ($variable in $collection) { # code to execute } Here’s an example of a for loop that iterates through a list of integers and displays the current value of the loop variable on each iteration:$numbers = 1, 2, 3, 4, 5
for ($number in$numbers) {
Write-Output “Current value: $number” } This will output the following: Current value: 1 Current value: 2 Current value: 3 Current value: 4 Current value: 5 You can also use a foreach loop, which has a similar syntax: foreach ($variable in $collection) { # code to execute } For example:$numbers = 1, 2, 3, 4, 5
foreach ($number in$numbers) {
Write-Output “Current value: $number” } Both for and foreach loops can be controlled using break and continue statements, just like in other programming languages. #### Does PowerShell have loop? Yes, PowerShell has several types of loops that you can use to execute a block of code repeatedly. The most common types of loops are for, foreach, and while. Here is an example of a while loop that counts down from 10 and displays the current value of the loop variable on each iteration:$count = 10
while ($count -gt 0) { Write-Output “Current value:$count”
$count– } This will output the following: Current value: 10 Current value: 9 Current value: 8 Current value: 7 Current value: 6 Current value: 5 Current value: 4 Current value: 3 Current value: 2 Current value: 1 You can also use a do-while loop, which has a similar syntax: do { # code to execute } while (condition) For example:$count = 10
do {
Write-Output “Current value: $count”$count–
} while ($count -gt 0) Both while and do-while loops can be controlled using break and continue statements, just like in other programming languages. #### How do you write a for loop script in powershell? To write a for loop script in PowerShell, you can use the following syntax: for ($variable in $collection) { # code to execute } Here’s an example of a script that defines a list of integers and then uses a for loop to iterate through the list and display the current value of the loop variable on each iteration:$numbers = 1, 2, 3, 4, 5
for ($number in$numbers) {
Write-Output “Current value: $number” } To run this script, you can save it to a file with a .ps1 extension and then execute it by running the powershell command followed by the path to the script file. For example: powershell C:\path\to\script.ps1 This will output the following: Current value: 1 Current value: 2 Current value: 3 Current value: 4 Current value: 5 You can also use a foreach loop, which has a similar syntax: foreach ($variable in $collection) { # code to execute } For example:$numbers = 1, 2, 3, 4, 5
foreach ($number in$numbers) {
Write-Output “Current value: $number” } Both for and foreach loops can be controlled using break and continue statements, just like in other programming languages. #### What are the different types of PowerShell loop? There are several types of loops that you can use in PowerShell: for loop: This loop is used to execute a block of code a specific number of times. The syntax is: for ($variable in $collection) { # code to execute } foreach loop: This loop is used to iterate over the elements of a collection. The syntax is: foreach ($variable in $collection) { # code to execute } while loop: This loop is used to execute a block of code repeatedly as long as a specified condition is $true. The syntax is:

while (condition) {
# code to execute
}

do-while loop: This loop is similar to the while loop, but it executes the block of code at least once before checking the condition. The syntax is:

do {
# code to execute
} while (condition)

Both while and do-while loops can be controlled using break and continue statements, just like in other programming languages.

#### What is the purpose of a for loop command?

The purpose of a for loop is to execute a block of code a specific number of times. It is often used when you need to perform a repetitive task with a known number of iterations.

#### Can we use == in for loop?

Yes, you can use the == operator in a for loop to compare values. For example:

for ($i = 1;$i -le 10; $i++) { if ($i == 5) {
Write-Output “Found 5!”
}
}

This loop will iterate through the values 1 to 10, and when it reaches 5, it will output the string “Found 5!”.

Here’s a more complete example that demonstrates how you can use the == operator in a for loop to search for a specific value in an array:

$numbers = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 for ($i = 0; $i -lt$numbers.Length; $i++) { if ($numbers[$i] == 7) { Write-Output “Found 7 at index$i”
break
}
}

This will output the following:

Found 7 at index 6

Note that you can also use the -eq operator to compare values in PowerShell. For example, you could write the above loop like this:

for ($i = 0;$i -lt $numbers.Length;$i++) {
if ($numbers[$i] -eq 7) {
Write-Output “Found 7 at index $i” break } } Both == and -eq are used to test for equality between two values. The main difference is that == is a comparison operator, while -eq is a cmdlet. Some people prefer to use -eq because it is more consistent with the naming conventions used in PowerShell cmdlets. #### Does for loop start 0 or 1? In a for loop, the loop variable is initialized to the start value before the loop begins, and then it is incremented or decremented on each iteration until the end condition is reached. By default, the loop variable is initialized to 0 and then incremented by 1 on each iteration. For example: for ($i = 0; $i -lt 10;$i++) {
# code to execute
}

This loop will iterate 10 times, with the loop variable taking on the values 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9.
However, you can use any start value and increment/decrement value that you like.

For example, you can start the loop variable at 1 and increment it by 2 on each iteration like this:

for ($i = 1;$i -le 10; $i += 2) { # code to execute } This loop will iterate 5 times, with the loop variable taking on the values 1, 3, 5, 7, and 9. You can also use a negative increment/decrement value to count down from a higher number to a lower number. For example: for ($i = 10; $i -ge 0;$i–) {
# code to execute
}

This loop will iterate 11 times, with the loop variable taking on the values 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, and 0.

#### PowerShell ForEach loop

The ForEach loop is a built-in construct in PowerShell that allows you to iterate over items in a collection, such as an array. Here is an example of how to use ForEach to loop through an array of strings:

$colors = “red”, “green”, “blue” ForEach ($color in $colors) { Write-Host “The color is$color”
}

This would output the following:

The color is red
The color is green
The color is blue

You can also use the ForEach-Object cmdlet to loop through the objects in a collection, like this:

Get-Process | ForEach-Object {
Write-Host “The process name is $_.Name” } There are many more options and ways to use the ForEach loop and ForEach-Object cmdlet in PowerShell. #### PowerShell for loop 1 to 10 To loop from 1 to 10 in PowerShell, you can use a for loop. Here is an example of how to use a for loop to count from 1 to 10: for ($i = 1; $i -le 10;$i++) {
Write-Host $i } This would output the numbers 1 through 10, one per line. You can also use a while loop to achieve the same result:$i = 1
while ($i -le 10) { Write-Host$i
$i++ } #### PowerShell for loop index To get the index of the current iteration in a for loop in PowerShell, you can use the loop variable itself. For example:$items = “apple”, “banana”, “cherry”
for ($i = 0;$i -lt $items.Count;$i++) {
Write-Host “Item $i:$($items[$i])”
}

This would output the following:

Item 0: apple
Item 1: banana
Item 2: cherry

Here, $i is the index of the current iteration and $items[$i] is the element at that index in the $items array.

You can also use the ForEach-Object cmdlet to iterate over the elements in a collection, like this:

$items | ForEach-Object -Begin {$i = 0} -Process {
Write-Host “Item $i:$($items[$i])”
$i++ } This would have the same output as the for loop above #### PowerShell for loop counter To keep a running count of the number of iterations in a for loop in PowerShell, you can use a counter variable that you increment within the loop. Here is an example of how to do this:$items = “apple”, “banana”, “cherry”
$counter = 0 for ($i = 0; $i -lt$items.Count; $i++) {$counter++
Write-Host “$counter:$($items[$i])”
}

This would output the following:

1: apple
2: banana
3: cherry

You can also use the ForEach-Object cmdlet to iterate over the elements in a collection, like this:

$items | ForEach-Object -Begin {$counter = 0} -Process {
$counter++ Write-Host “$counter: $($items[\$i])”
}

This would have the same output as the for` loop above.

#### Final Thoughts

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 idea.

You’ve learned the fundamentals of PowerShell for loop statements in this guide. You’ve learned about its basic structure, logic, and flow, as well as how to utilize it for various reasons from numerous examples.

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

With the information you’ve gained from this post, you ought to be able to discover additional methods to use loop to automate your routine activities.

As a tech writer, I deeply understand how technology impacts our daily lives. From the devices to the software we rely on, I strive to help others navigate the complex world of technology and make informed decisions about their tech purchases.