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.

Sponsored Content


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.

Sponsored Content


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) { }

Sponsored Content


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!

Sponsored Content


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.

Sponsored Content

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

FEATURED POSTS

network discovery keeps turning off server 2016

How to Fix Network Discovery If it Keeps Turning Off in Server 2016

Does network discovery keep turning off in your Windows server 2016? It is likely that one of its dependent services is not...
how to install windows 10 1903 update manually

How to Install Windows 10 1903 Update Manually

Windows 10 1903 Update was released in May, 2019. But some users are not yet offered the update via automatic update. The...
spotify web player not working

Spotify Web Player Not Working [Fixed]

Introduction Spotify Web Player may stop working for you with the following error messages: "Spotify Web Player an Error...
DISM.exe /Online /Cleanup-Image /Restorehealth

DISM.exe /Online /Cleanup-Image /Restorehealth Explained

What is DISM.EXE /Online /Cleanup-image /RestoreHealth? "DISM.exe /Online /Cleanup-Image /Restorehealth" is a DISM command that repairs issue with the...
DHCP Relay agent

DHCP Relay Agent: Configuration in Windows Server 2016

What is a DHCP Relay Agent? A DHCP Relay Agent allows DHCP clients in a different network subnet to...

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

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 ...
How to Check Windows 10 Version

How to Check Windows 10 Version in 4 Easy Ways

Introduction Wondering how you can check your version of Windows 10? Here are 4 easy ways for you -...
printer offline

5 Ways to Restore Your Printer Online If Status is Offline

Introduction Is your printer offline? Setting it online is very simple but sometimes it is more than just setting...
WSCRIPT and CSCRIPT Commands: Syntax, Parameters, Examples

WSCRIPT and CSCRIPT Commands: Syntax, Parameters, Examples

Introduction WSCRIPT is the Windows-based version of Windows Script Host while CSCRIPT is the command-prompt-based version. This guide...
windows safe mode

2 Easy Ways to Start Windows 10 Safe Mode

Introduction In previous versions of Windows you could start safe mode by pressing F8. But in Windows 10, F8...

RECENT POSTS

disable cortana windows 10 featured

How to Disable Cortana in Windows 10 (2 Methods)

Introduction Some Windows 10 users may not like Cortana. Solution? Disable Cortana. You are probably reading this because you...
bootrec /fixboot access is denied

How to Fix BootRec /FixBoot Access is Denied Error in Windows 10

Introduction BootRec /FixBoot Access is Denied Error in Windows 10? This error is likely caused by corrupt EFI directory.
Reset Windows 10

How to Reset Windows 10 (2 Methods)

Introduction If your Windows 10 is broken, one available way to fix it is to use Windows 10 reset....
system restore windows 10

How to Enable and Use System Restore in Windows 10

Introduction System restore in windows 10 is a very important tool that is probably ignored by most users. But...
windows has stopped this device code 43

How to Fix Windows Has Stopped this Device Code 43 Error

Introduction Sometimes you may receive "Windows has stopped this device code 43" error. This error is likely to come...
Windows could not automatically detect this network's proxy settings

How to Fix “Windows Could not Automatically Detect this Network’s Proxy Settings”

Introduction You suddenly lose the ability to connect to the internet. Then you run network troubleshooter and it returns...
printer offline

5 Ways to Restore Your Printer Online If Status is Offline

Introduction Is your printer offline? Setting it online is very simple but sometimes it is more than just setting...

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...
windows 10 search featured

How to Fix Windows 10 Search If it Stops Working

Introduction Are you having troubles with Windows 10 search? Apparently, it is a fairly common problem with a number...
oooops, something went wrong. reload

How to Fix “Oooops something went wrong. reload” Spotify Error

Introduction If you receive "Oooops something went wrong. reload" Spotify error, do not panic. The fix is simpler than...

MUST READ

Websites Like Craigslist for Apartments

Top 5 Websites Like Craigslist for Apartments

Craigslist is a local classified Ads website with 7 sections including apartment rent. It is a brilliant site but using other websites...
Windows Boot Manager (BOOTMGR)

Windows Boot Manager: Edit Bootmgr, Fix Boot Errors in Windows 10

What is Windows Boot Manager? Windows Boot Manager (Bootmgr.exe) is a component of the new Windows Boot Loading Architecture...
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...

Powershell If Else Explained: Syntax and Examples

Introduction PowerShell If Else statement runs a command if a specified condition is met. The Else part of PowerShell...

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

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