Advertisements

PowerShell ForEach: Syntax, Parameters, Examples

-

|

What is PowerShell ForEach?

PowerShell ForEach (ForEach PowerShell) is a PowerShell construct used in iterating through values in a collection of items. The PowerShell ForEach loop allows you to loop through a collection of items and perform a defined task (command) on each item. The key word here is “iterating”.

In this tutorial I will use ‘PowerShell ForEach’ and ‘ForEach PowerShell’ interchangeably.

How PowerShell ForEach Iteration Works

To iterate through a collection of items, you take the first item in the collection and performs an action. When you complete the task on the first item, you take the next item and perform the same action on the item. Then You continue to go back until you have gone through all the items in the collection. Think of PowerShell ForEach this way.

As an example, let’s say you have a crate of egg containing 12 eggs and you wish to break all the eggs. Say you are required to break each egg with a knife such that you cut neatly through the centre of the egg.

Advertisements



You have to iterate through the crate which contains the collection of eggs. To achieve this, you take the first egg, cut it through neatly, keep it aside and take the next. This is what ‘ForEach PowerShell’ does.

To give a PowerShell example, lets run a very simple PowerShell command Get-ChildItem:

Get-ChildItem

The result of the command is shown below:

PowerShell-ForEach-Get-ChildItem
Get-ChildItem

Notice that the Get-ChildItem command returned a collection of items. For this example, let’s concentrate on the ‘Name’ column. Assuming you wish to return only the items in the collection with a Name beginning with the letter ‘D’. You will need PowerShell ForEach construct to achieve this.

Later in this article, we will come back to this example.

PowerShell ForEach Syntax

Before I introduce you to ‘ForEach PowerShell’ Syntax, let me discuss a concept we will be using called ‘Variables’. A PowerShell variable stores values in units of memory. To create a variable in PowerShell, you assign the variable a name. The name begins with a dollar sign ($) followed by a text string. An example of a variable is $Info or $MyInfo.

The syntax of a PowerShell ForEach construct is shown below:

ForEach ($item in $collection) {Perform a task based on a powershell command} 

The syntax of a ‘ForEach PowerShell’ loop starts with the word ‘ForEach’.
The word ‘ForEach’ is then followed by brackets ‘()’; and finally ‘{}’ block. So, to aid your understanding of the ForEach PowerShel loop, lets have the syntax without any values:

ForEach ( ) { } 

Whenever you want to script a ForEach PowerShel loop, simply start by typing ForEach ( ) { } into your editor. Then populate the ForEach loop with values. This is one trick to PowerShell scripting. Always start from the basic and gradually add values! You can read a bit more about PowerShell scripts on the about_Scripts page.


Understanding the ForEach Loop Syntax

In the PowerShell ForEach syntax, you will notice two variables enclosed in the bracket ‘()’. The second variable, $collection contains the collection of items. The first variable, $item is a variable assigned to each item in the collection as you iterate through the collection.

The construct of a ‘ForEach PowerShell’ loop is very straight forward. It simply says: ForEach $item in ‘the’ $collection, perform the task(s) enclosed in the ‘{}’ block.

Following up from where we stopped, after we have typed ‘ForEach ( ) { }’, the next step will be to add a variable for each item in the collection; followed by the variable storing all the collections. Below is the syntax without any values.

ForEach ( ) { } 

Let’s include the second bit in the ‘ForEach PowerShell’ loop:

ForEach ($item in $collection) { }

Adding Values Within the ‘()’ PowerShell ForEach Loop

I believe you have a good grasps of the ‘ForEach PowerShell’ loop construct. Next, I will show you how you can add values within the bracket ‘()’ part of the ‘ForEach PowerShell’ loop. Refer to the Get-ChildItem we ran earlier in the article.

 Get-ChildItem 

The result is shown below:

As I mentioned earlier, the Get-ChildItem returns a collection of items. To start with, let’s store the collection in a variable called $Results. The command accomplishes this.

 $Results = Get-ChildItem 

Creating a PowerShell variable is as simple as that! Variable name equals (=) Variable content. In order to confirm that the variable, $Results stored the information previously returned by the Get-ChildItem, execute the command below:

$Results 

The command returns the results shown below.

So, the variable contains the collections. Before we construct our ‘ForEach PowerShell’ loop, we need to assign a variable to each item in the $Results collection.

Let’s call the variable $Result. Do not allow the similarity of the two variables confuse you. Our original collection was stored in $Results WITH ‘s’. The variable that will store each item contained in the $Results collection is $Result WITHOUT ‘s’. Note that you could name this variable anything.

Enough of talks. Let’s construct our PowerShell ForEach. Remember the first step? Construct the ‘ForEach PowerShell’ loop without any content. Can you do it on your own? See it below:

ForEach ($Result in $Results) { }

Running Commands Within the PowerShell ForEach ‘{}’ block

Let’s add commands to the the ‘{}’ portion of the PowerShell ForEach. Before we proceed, please refer to the result of the Get-ChildItem command once more. Earlier in the article, I said that if you wish to return only the items in the collection with a Name beginning with the letter ‘D’, the ForEach PowerShell will come in handly. Let’s see how this will work.

Introducing the “IF” Statement

Before we proceed further, let me introduce you to another PowerShell concept called ‘IF’. You can get more information about ‘IF’ statements
by referring to the about_If page. I will provide a quick overview of the ‘IF’ statement. An ‘IF’ statement runs a code if a specified condition is met. The syntax of an ‘IF’ statement is shown below:

IF (condition1) {Exdecute the following codes} ELSEIF (condition2) {Exdecute the following codes} ELSE {Exdecute the following codes} 

Providing a detailed explanation of the ‘IF’ statement is beyond the scope of this aritcle. Please refer to the about_If page for details.

Back to the ForEach PowerShell Example

Going back to our PowerShell ForEach example, we want to test the collections stored in the $Results variable for items with name starting with the letter ‘D’. To achieve this, we simply add an ‘IF’ statement within the ‘{}’ block of the PowerShell ForEach loop. Below is where we left off the command earlier:

ForEach ($Result in $Results) { } 

To proceed, add an ‘IF’ statement within the ‘{}’ as shwon below.

ForEach ($Result in $Results) { IF($Result -LIKE 'D*') {} } 

Notice that I have not finished the ‘IF’ statement block? I intentionally left out adding anything within the ‘{}’ portion of the ‘IF’ command block. I want you to understand the logic behind anything I add. Look at the command above and compare it with the previous command. The difference is “IF($Result -LIKE ‘D*’) {}” placed within the ‘{}’ block of the PowerShell ForEach loop construct.

Now that we have added a condition to the ‘IF’ statement, we want to tell the ‘IF’ statement what to do if that condition is TRUE. This is achieved by adding a command within the ‘{}’ block of the ‘IF’ statement. Here you go!

ForEach ($Result in $Results) { IF( $Result.Name -like 'D*') {$Result } } 

Boom! The command returned only items in the collection with names as shown below. What we did was to simply return items in the $Result variable if the condition in the ‘IF’ statement is true.

Can you see how easy it is to write PowerShell scripts!

You can apply this principle in any scripting condition requiring you to use the ForEach PowerShell!

Advertisements



Running commands Directly to Create a Collection in a ForEach PowerShell

I started the previous section by storing the collections obtained from the Get-ChildItem command into a variable called $Results. We will be able to achieve the same outcome without storing the collections in a variable. Next, we will run the Get-ChildItem command directly in place of the $Results variable. Let’s go back to the original state of command as shown below:

ForEach ($Result in $Results) { } 

Next, let’s replace the $Results variable with the Get-ChildItem command

ForEach ($Result in Get-ChildItem) { } 

The logic already explained earlier in this article applies. The variable, $Result is assigned to each item in the collection returned by the Get-ChildItem command. Like we did earlier, lets introduce the ‘IF’ statement block.

ForEach ($Result in Get-ChildItem) { IF( $Result.Name -like 'D*') {$Result } } 

The Result is similar to our previous result!

One last word before we move on to ForEach PowerShell. The reason you might want to store the collection in a variable rather than run the command directly is because some commands may be too long to manage conveniently within the PowerShell ForEach loop construct. In such instance, you are better off running the command outside the ForEach PowerShell construct and storing it in a variable.

PowerShell ForEach Examples

In the last section of this article, I will give you real life, system admin application of the PowerShell ForEach loop. In this example, I will show you how I used the ‘ForEach PowerShell’ loop construct in my Get-InactiveADUsers (Function available on the Microsoft script Gallery).

The Get-InactiveADUsers function reports users that have not logged on to an Active Directory domain in X days. The Get-InactiveADUsers Function has a parameter called ‘SearchBase’. It allows a user to specify the Active Directory container to search for ‘inactive’ users – users that have not logged on for ‘X’ number of days.

Example of PowerShell Variable

The ‘SearchBase’ parameter specify the user-friendly name of the Active Directory container. But my command that searches for users requires
the distinguishedName (DN) of the object. My first task is to take the name provided by the user via the ‘SearchBase’ parameter and convert it to the DN format. The command below achieves this purpose (Copied command as shown in line 101 of the Get-InactiveADUsers function).

$SearchLoc = (Get-ADObject -LDAPFilter "(Name=$SearchBase)" -Properties name -server $ADServer).distinguishedName 

You should be able to note that I stored the result of the Get-ADObject command in a variable called $SearchLoc. But there is one more problem. There might be more than one Active Directory container in the AD forest with the same name. I will need to loop through the $SearchLoc collection with our famous ForEach PowerShell loop. To loop through the $SearchLoc variable, I executed the command below:

ForEach ($DN in $SearchLoc) { $Users = Get-ADUser -Server $ADServer -SearchBase $DN -Filter * -Properties lastlogondate | Where-Object {($_.lastlogondate -le $LastLogonDate) } 

Just like our previous example, the individual items in the $SearchLoc variable is stored in the $DN variable. For the avoidance of doubt, the variable $ADServer is also a parameter in the Get-InactiveADUsers function. The information is provided by the user. The function has some other commands but you get the gist. To get the function, download it from the link provided in the “References and further reading” section
below.

Advertisements



Conclusion

Powershell ForEach is a very important command for writing great PowerShell scripts. I hope you have gained a thing or tool about this command.

If you have any question or comment, use the “Leave a Reply” form at the end of this page. You could also simply vote Yes or No to let me know what you think about the guide. Alternatively, share your experience about where and how you’ve used Powershell ForEach for other readers to benefit.

Other Helpful Guides

Additional Resources and References


LEAVE A REPLY

Please enter your comment!
Please enter your name here

LATEST DEALS

Exclusive Student Offer_Save 10% on selected Surface devices

FEATURED POSTS

How to Change Administrator Name in Windows 10 (4 Methods)

How to Change Administrator Name in Windows 10

Introduction This guide demos how to change administrator name in Windows 10. There could be...
How to Setup WhatsApp Auto Reply in an Android Phone

How to Setup WhatsApp Auto Reply in an Android Phone

Introduction This guide demos how to setup Whatsapp auto reply in an Android phone. Steps...
How to Set Out of Office Auto Reply in Outlook, Outlook.com and Gmail

How to Set Out of Office Auto Reply in Outlook, Outlook.com and Gmail

Introduction This guide demos how to set out of office auto reply in Outlook, Outlook.com and Gmail.
How to Take Ownership of Folder in Windows 10

How to Take Ownership of Folder in Windows 10 (2 Methods)

Introduction This guide demos 2 methods to take ownership of folder in Windows 10. Options to...
How to Install Windows Server 2019 from USB

How to Install Windows Server 2019 from USB

Introduction This guide demos how to install Windows Server 2019 from USB. Steps to Install...

ADVERTISEMENTS

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

BEST OF ITECHGUIDES

PowerShell Not Equal

PowerShell Not Equal Operator: Applications, Examples

Introduction PowerShell Not Equal Operator is one of the Comparison Operators. PowerShell Not Equal (-ne) compares two values. If...
Excel Not Equal

Excel “Not Equal” Comparison Operator: Syntax, Examples

Introduction Excel "Not Equal" is a Comparison operator that compares two values. "Not Equal" will return TRUE if the...
iPhone SE vs iPhone 6s compared - which to buy

iPhone SE vs iPhone 6s Compared: Which to Buy

Introduction Considering whether to buy iPhone SE vs iPhone 6s? Not sure which is better? When I am trying...
Group Policy, GPResult, Group Policy Object and RSoP

Group Policy, Group Policy Object and RSoP Explained

Introduction This guide gives an overview of Group Policy, RSoP (Resultant Set of Policy) and Group Policy Objects.
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...

RECENT POSTS

C:\G-Drive\Work Tools\Products Portal\1. New Business\2. Content Sites\1. iTechGuides.com\Posts\1. HOW TO\Microsoft\MS Office\Microsoft Word\how to add more rows to a table in word

How to Add More Rows to a Table in Word and Google Docs

Introduction This guide demos how to add more rows to a table in Word. It also has a...
How to Create a Bar Chart in Excel and Google Sheets

How to Create a Bar Chart in Excel and Google Sheets

Introduction This guide demos how to create a bar chart in Excel and Google Sheets. A bar chart is...
How to Change Administrator Name in Windows 10 (4 Methods)

How to Change Administrator Name in Windows 10

Introduction This guide demos how to change administrator name in Windows 10. There could be...
How to Create a Pie Chart in Excel and Google Sheets

How to Create a Pie Chart in Excel and Google Sheets

Introduction This guide demos how to create a pie chart in Excel and Google Sheets. A pie chart is...

iTechGuides’ Top 10 Online Games

The gaming world is getting bigger day by day. Many people are getting engaged to play online games worldwide.

How to Open Local Security Policy in Windows 10 (5 Methods)

Introduction This guide demos how to open local security policy in Windows 10. Options to...

How to Change Network from Public to Private in Windows 10

Introduction This guide demos 2 methods to change network from public to private in Windows 10.
How to Disable Touchpad in Windows 10 for Dell or HP Laptop

How to Disable Touchpad in Windows 10 for Dell or HP Laptop

Introduction This guide demos how to Disable Touchpad in Windows 10 for a Dell or HP laptop.

How to Change Account Picture in Windows 10 (2 Methods)

Introduction This guide demos 2 methods to change account picture in Windows 10. Windows 10...
How to Create Xbox Live Account

How to Create Xbox Live Account (2 Methods)

Introduction This guide demos 2 methods to create Xbox Live account. Options to Create Xbox...

ADVERTISEMENTS

MUST READ

PowerShell Not Equal

PowerShell Not Equal Operator: Applications, Examples

Introduction PowerShell Not Equal Operator is one of the Comparison Operators. PowerShell Not Equal (-ne) compares two values. If...
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...

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...
How to Delete Hotmail Account (Outlook.com Account)

How to Delete Hotmail Account (Outlook.com Account)

Introduction This guide demos how to delete Hotmail account. Hotmail.com has been replaced by Outlook.com.

Our Top 10 PS4 Adventure Games

Are you ready to dive into the fantasy world of PS4 adventure games? You are at the right place.

LATEST DEALS

Exclusive Student Offer_Save 10% on selected Surface devices

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