Powershell For Loop Explained: Syntax and Examples

-

|

Introduction

“Powershell For Loop” (or Statement) is a construct that is used to run a command in a block while a condition evaluates to True. The word “while” is essential here as “Powershell For Statement” is used to iterate an array of values and to operate on a subset of these values. The For Loop will continue to repeat as long as the condition is True.

The For Loop is different from PowerShell ForEach Statement. While For Loop iterates an array of values and operates on a subset of these values, ForEach Statement iterate all the values in an array. The key difference is in the words subset and all.

If it is still confusing, do not worry. This guide offers a simplified explanation of “Powershell For Loop”, including Syntax and applicable examples.

Advertisement

Powershell For Loop Syntax

The Syntax of “Powershell For Loop” is:

for (<init>; <condition>; <repeat>)
{<statement lists>}

Powershell For Loop Parameters

This section explains the parameters in the PowerShell For Loop Syntax.

Init – is used to set a starting variable for the For Loop. Typically, the Loop will evaluate this value first based on the condition in the condition block. The next time the For Statement runs, the value in the Init will be adjusted based on the Repeat block. Then the new value will be evaluated based on the condition. And so on. An example of Init value for a For Loop could be “$a = 1”, without the quotes.

Condition – is where a condition is placed to evaluate values from the Init block. PowerShell evaluates the value in the Condition block and determines whether it is $True or $False. If the condition is $True, the commands in the statement lists block will run. The PowerShell For Loop will continue to repeat until the condition becomes $False. Then PowerShell will exit.

Repeat – is used to add commands that are evaluated each time the loop repeats. Refer to the example I gave in the Init parameter explanation. If Init is “$a = 1”, the Repeat value could be $a++. This tells PowerShell to increment the value in the Init value by 1 each time the PowerShell For Loop repeats. So, the first time the For Statement runs, the Condition block will check with the value of 1. When it runs next, it will check with 2 (1+1) and so on. As I said earlier, the For Loop will continue until the condition evaluates to $False.

Statement list – is the actual command that is executed each time the PowerShell For Loop repeats. An example command could be “Write-Host $a”. This will simply display the value each time the Loop repeats.

Powershell For Loop Examples

Summary
The PowerShell For Loop has 2 main blocks. The first block is enclosed in (), the second in {}. Moreover, within the () block, there are 3 sub-blocks. Init, Condition and Repeat blocks. Finally, the {} block contains the command that runs each time the For Statement repeats.

With this in mind, this section will be used to share some examples of the PowerShell For Loop.

Powershell For Loop Example 1: Basic

My first example is very basic. I want to display the numbers 1, 2 and 3. To do this, I will set an Init value of 1 ($a = 1). Then add a condition to evaluate if the Init value is less than or equal to 3 ($a -le 3).

Next, I will add a value of $a++ in the Repeat block. This will increment the Init value of the Init value, $a by 1 each time the Loop repeats. Finally, I will add a code in the Statement list block (Write-Host $a). This will display the values of a$ on the screen.

Here is the code

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

and the result…

Powershell For Loop Example 1: Basic
Advertisement

Powershell For Loop Example 2: Multiple Operations

The Init, Condition and Repeat blocks of the PowerShell For Lop can take multiple operators. The following examples illustrate how to use multiple operators in the Powershell For Loop.

The original Syntax of the For Loop is:

 for (<init>; <condition>; <repeat>)
{<statement lists>}

In my previous example, I gave this basic example:

 For($a=1; $a -le 3; $a++) {Write-Host $a} 
If you look closely you will notice that the Init, Condition and Repeat blocks are separated by a semicolon, ;.

To add multiple Init operators, we enclose each in a () and separate them with a coma ,. If you add multiple Init operators, you will then need to have multiple Condition and Repeat operators.

Multiple Condition include Logical Operators for additional comparison of 2 conditions. Click about_Logical_Operators to read about them.

Here is an example of how to use multiple operators in a PowerShell For Loop:

for( ($a=1),($b=1); $a -le 3 -and $b -le 5; $a++,$b++) 
{
Write-Host $a
Write-Host $b
}
To run this script open PowerShell ISE. Then copy the code and paste the code in PowerShell ISE. Finally, click Run Script.

Here is the result of the previous script

 Powershell For Loop Example 2: Multiple Operations

Notice that the output for both $a and $b variables went up to a maximum of 3 even though $b has the condition $b -le 5. The reason is the -and logical operator.

Here is why:

Each time the Loop repeats, the -and operator checks whether the values returned by $a -le 3 AND $b -le 5 are the same. It is only when they are the same that the Loop will execute the command in the {} block.

So, even though $b -le 5 could have resulted in 4 and 5, during the Loop, the values will NOT be used for execution because they will not be the same value as $a -le 3, which produces a maximum of 3 – less than or equal to 3.

Conclusion

“Powershell For Loop” (or Statement) construct is useful for building scripts for automating Windows tasks. I hope this guide simplified it enough.

If you have any question or comment, use the “Leave a Reply” form at the end of the page. Alternatively, you could share your experience using PowerShell For Loops.

Other Helpful Guides

Additional Resources and References

LEAVE A REPLY

Please enter your comment!
Please enter your name here

FEATURED POSTS

How to Share a Folder in Windows 10 (3 Methods)

Introduction This guide demos how to share folder in windows 10. It covers 3 methods. Options...

How to Map Network Drive in Windows 10 (5 Methods)

Introduction This guide demos 5 methods to Map Network Drive in Windows 10. Options to...
How to Install Windows 10 1909 Preview Build

How to Install Windows 10 19H2 Preview Build

Introduction If you are a member of Windows 10 Insider Program you can install Windows 10 19H2 Preview Build....

How to Sign in to Windows 10 with a Microsoft Account

Introduction When you installed Windows 10 you may have created and signed in with a local account. You can...
Disable IPv6 in Windows 10

How to Disable IPv6 in Windows 10 (3 Methods)

Introduction This guide demos 3 methods to disable IPv6 in Windows 10: Disable IPv6 from...

Advertisement

TRENDING POSTS

Remote Desktop Connection

Remote Desktop Connection an Internal Error Has Occurred [Fixed]

Introduction I recently received the error message "Remote Desktop Connection an Internal Error Has Occurred". It was strange because...

Find My Samsung: Register and Use Samsung Find my Mobile

Introduction Ever wondered how you could find your Samsung phone if you lost it? Find my Samsung or Samsung...
What is the Difference Between PowerShell and CMD?

Windows Powershell vs CMD: Differences and Similarities

Introduction This short guide compares Windows PowerShell vs CMD (Windows command prompt). I will cover the history and nature...
Spotify No Longer Supports this Version of Microsoft Edge

Spotify No Longer Supports this Version of Microsoft Edge [Fixed]

Introduction When you open Spotify web player on Microsoft Edge, you may receive the error message "Spotify No Longer...
Windows 10 Won't Boot

Windows 10 Won’t Boot With Black Screen? 3 Ways to Fix It

Why Won't Windows 10 Boot Up? If your Windows 10 stops with a black screen, the first question in...

Advertisement

BEST OF ITECHGUIDES

windows update 0x8024401c

How to Fix Windows Update Error 0x8024401c in Windows 10

Introduction Received Windows Update 0x8024401c error in Windows 10? You have done this and done that yet, the error...
foreach in file powershell

How to Iterate the Content of a Text File in Powershell in 2 Easy...

Introduction If you have a text file with data you wish to use, you can use PowerShell Get-Content ...
NTFS Permissions with Share Permissions

NTFS Permissions with Share Permissions Compared

Introduction Combing NTFS permissions with share Permissions increases folder security within a network. Every Windows Administrator should have a...
How to Calculate Variance in Excel

How to Calculate Variance in Excel

Introduction Variance measures the spread between numbers in a data set. You can calculate variance in Excel using the...
windows modules installer worker high cpu 2

How to Fix Windows Modules Installer Worker High CPU

Introduction If Windows Modules Installer Worker has high CPU usage, it may slow your computer down. Windows Modules Installer...

RECENT POSTS

How to Enable Hyper-V in Windows 10 (3 Methods)

How to Enable Hyper-V in Windows 10 (3 Methods)

Introduction This guide demos 3 methods to enable Hyper-V in Windows 10. To install Hyper-V...
RSAT Tools in Windows 10 Explained: Plus How to Install RSAT

RSAT Tools in Windows 10 Explained: Plus How to Install RSAT

Introduction Starting from October 2018 (1809) update, RSAT Tools became part of Windows 10. From this version of Windows...

How to Enable RSAT for Active Directory in Windows 10 (3 Methods)

Introduction This guide demos 3 methods to enable Active Directory in Windows 10. It is not exactly enabling "Active...
How to Install Windows 10 1909 Preview Build

How to Install Windows 10 1909 (19H2) Preview Build

Introduction Windows 10 1909 Preview is available for Windows Insiders. Made available early September, 2019 you have to be...
How to Install RSAT in Windows 10 (3 Methods)

How to Install RSAT in Windows 10 (3 Methods)

Introduction This guide demos how to Install RSAT in Windows 10. Starting with Windows 10...

How to Share a Folder in Windows 10 (3 Methods)

Introduction This guide demos how to share folder in windows 10. It covers 3 methods. Options...
Configure Map Network Drive with Group Policy

Map Network Drive in Windows 10 with Group Policy

Introduction This guide demos how to map network drive with group policy. This guide is...

How to Map Network Drive in Windows 10 (5 Methods)

Introduction This guide demos 5 methods to Map Network Drive in Windows 10. Options to...
How to Download Windows 10 ISO with Media Creation Tool

How to Download Windows 10 ISO with Media Creation Tool

Introduction This guide demos the steps to download Windows 10 ISO. You can download Windows 10 ISO with Media...

How to Install Windows 10 from Network Boot (Via WDS Server)

Introduction This guide demos how to install Windows 10 from network boot. The steps discussed in...

Advertisement

MUST READ

windows update stuck featured

How to Get Windows Update to Work If Download is Stuck at 0%

Experiencing Windows Update stuck at 0%? Have you waited for hours already, yet to progress? You are not alone! A lot of...
Amazon Merch

Amazon Merch: Your Definitive Guide to Merch by Amazon

What is Amazon Merch? Merch by Amazon (MbA or Amazon Merch) is a T-shirt Print-On-Demand platform that allows you...

How to Fix “BootMgr is Missing” Error in Windows 10

Introduction If you receive Fix "BootMgr is missing" Error in Windows 10, the default response is panic! But you...
Active Directory FSMO Roles

Active Directory FSMO Roles Explained

Introduction This article offers a simplified explanation of the 5 Active Directory FSMO (pronounced "FisMO") roles.
windows 10 lock screen timeout

How to Change Screen Time Out Setting in Windows 10

Introduction There are two easy ways to change Windows 10 lock screen timeout settings: Desktop...

By using this website you agree to accept our Privacy Policy and Terms & Conditions