Home Tech 7 Examples of How to Use PowerShell For Loops

7 Examples of How to Use PowerShell For Loops

0

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 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"}

powershell for loop

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.

7 Examples of How to Use PowerShell For Loops

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:

7 Examples of How to Use PowerShell For Loops

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:

7 Examples of How to Use PowerShell For Loops

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:

7 Examples of How to Use PowerShell For Loops

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 Examples of How to Use PowerShell For Loops

7 Examples of How to Use PowerShell For Loops

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" 
}

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.