Powershell ForEach Loop: A Versatile Option in the Scripting World

Looping is a fundamental concept in all programming languages. You can use looping to perform an action uniformly on all the required items, inside and outside a collection. That said, you have many ways to loop through collections, and ForEach is one of them.

In this article, I’ll talk about what ForEach is and how you can use it in Windows PowerShell. Let’s get started. 

What Is ForEach?

ForEach is a common looping mechanism in Windows PowerShell. Essentially, it reads an object from a collection and then performs a specific action on it on a need-to basis. It finally exits after it reads the last object in the collection. 

From a programming standpoint, these collections are often arrays or hashtables. An array contains individual objects while a hashtable has a collection of key-value pairs

You can understand the mechanism with a simple example. Let’s say we have an array of numbers and want to increment each value by 12. That is, we start with:

$array = 1,2,3,4,5

Then, we want to increase the value of every element by 12 to get:

$array = 13,14,15,16,17.

Illustration of an individual coding on a laptop against a background of code snippets
Do you program through a ForEach loop?

At first glance, this may seem easy, but updating every element’s value in an array is cumbersome. In this example, we have five values, but in the real world, you’ll have hundreds of thousands of values in an array. This makes manual changing almost impossible and error-prone. This is why we need loops.

In PowerShell, you have 3 ways to implement the ForEach looping mechanism, and we’ll look into each next.

Method 1: Using the ForEach Statement

The first option is to use the PowerShell ForEach statement. This is PowerShell’s internal keyword. It’s not a function or a cmdlet. Instead, it’s just a statement that tells PowerShell to loop through an array/hashtable, executing the instructions on every object in the array.

The format or syntax of ForEach Statement is the following:

ForEach ($value in $array)

{

Perform an action.

}

Note that the word in is a reserved word in PowerShell and you must use it in the ForEach loop. A reserved word has a fixed meaning in PowerShell. You also can’t change or redefine it. 

Going back to our example of incrementing the value in an array by 12, the loop will look like this:

$array = 1,2,3,4,5

ForEach ($number in $array)

{

$number = $number + 12

}

After executing this code, print the values in $array and PowerShell will display 13,14,15,16,17. How does this work?

The ForEach loop starts with the first element, 1, and stores the element in a temporary variable, called number. Then, the loop adds 12 to this number in the first iteration. Next, it’ll move to the next element, 2, and add 12 to this number. The process goes on until PowerShell has iterated through all the elements in the array. After it adds 12 to the last element, the code will exit the loop automatically and move to the next line of code. 

This option is the second-fastest among the three options I discuss in this article. It’s faster than the next option because PowerShell doesn’t have to search cmdlets or libraries. It can just execute the code as is. This option is also ideal if you’re after readability.  

Let’s move to the second method now. 

Method 2: The ForEach-Object Cmdlet 

The second method is to use the ForEach-Object cmdlet that performs a specific action on all the elements in a collection. For now, it seems like the cmdlet is the same as the loop option. Looking closer, though, you’ll find you can pipe the input directly to the cmdlet. This cmdlet also supports the function’s Begin, Process, or End blocks. This way, you can decide if ForEach will execute a specific action before, during, or after the instructions. That’s how granular you can get with this cmdlet.

Let’s see an example to understand how to use the ForEach-Object cmdlet.

We go back to our 12-increment example. 

1, 2, 3 | ForEach-Object -Process {$_+12}

13

14

15

Here, you’re taking three integers and using the cmdlet to add 12 to each. The process also displays the results for you. What’s the difference between the ForEach statement and the ForEach cmdlet? The cmdlet option is the slowest among the three options. This performance difference isn’t so evident in small sets but can be significant in large sets. 

Let’s look at a more real-world PowerShell loop example now.

Get-Process | ForEach-Object -Begin {Get-Date} -Process ProcessName -End {Get-Date}

In the above example, the ForEach-Object gets a process object from the Get-Process command. The cmdlet then displays the current date and time, ProcessName parameter’s value, and the date and time after processing.

A cmdlet advantage is that you can set the ThrottleLimit parameter to limit the number of parallel scripts at any time. This parameter optimizes resource usage and improves your computer’s performance. This makes cmdlets perfect when you’re running parallel scripts. Otherwise, go for the next option, since it’s the fastest. 

Method 3 : The foreach() Method

The third option is the ForEach() method. It has become a built-in method in every array after PowerShell’s upgrade to v4. You can also execute the instructions in this method on every array element.

Circling back to our +12 example, we can write the same logic in a single line. 

$array. ForEach({$_ +12})

How is this different from the other two? At first glance, all three methods look the same and will give identical results. That said, this method is the fastest among all three options. Speed, in turn, can make a significant difference when you do complex operations on a large array. Another advantage is that this method also reduces and compacts the code, and leads applications to run faster.

Let’s now compare all three methods visually.

Methods Round-Up

We’ve seen three ways to use PowerShell ForEach. Your choice depends on your code, what you want to achieve, and the impact on your application’s performance. This table will give you an idea of which option to use and when.

Objective/ForEach MethodStatementcmdletForEach () Method
Application performance
Pipe inputs directly
Run parallel scripts
Code readability

Final Thoughts

ForEach is a popular looping mechanism in PowerShell that helps you perform specific actions on every object in a collection. In this article, we learned 3 ways to execute this loop. You want to choose the appropriate option for your code based on your programming logic and performance considerations. 

FAQs

What is ForEach in PowerShell?

ForEach is a programming language construct that allows you to loop through the elements in a collection. The simplest example is the process of iterating through all the elements in an array and doing the same action on every element. This looping mechanism optimizes code readability, application performance, and memory usage.

Can I use $_ in the PowerShell ForEach loop?

Yes. You can use $_ in the PowerShell ForEach loop. This $_ denotes the current item being processed. It’s the input on which specific instructions described within the ForEach brackets are performed. An example is $array. ForEach({$_ +12}). This option works on all methods introduced after PowerShell v3.0

Is there more than one way to execute ForEach looping in PowerShell?

Yes. You have 3 ways to implement the looping construct in PowerShell, namely ForEach statement, ForEach-Object cmdlet, and ForEach() method. Each option comes with pros and cons, so the choice depends on your requirements and programming logic. For example, if readability is your objective, go with the ForEach loop. While if you’re looking to pipe inputs and do something before and after processing, the cmdlet is your best option. Lastly, if application performance is your top priority, the ForEach() method is your best choice. 

Is the ForEach-Object cmdlet slower than the ForEach statement and ForEach() method?

Yes. The ForEach-Object cmdlet is the slowest of the three options. It’s slow because cmdlets have to connect to the Microsoft Certificate Trust List (CTL) URLs to verify the certificate. It’ll only execute after doing this. The ForEach statement is faster while the ForEach() method is the fastest. If you have limited resources, make sure to avoid the cmdlet method.

Are For and ForEach the same?

No. For and ForEach are different looping implementations in PowerShell. The biggest difference is that ForEach can work only on an element in a collection. The For loop can work on any data and not just collection items. In effect, both loops essentially perform the same function, but the For loop is more efficient. This is because the For loop checks a condition only once, while the ForEach loop has to check the same condition twice. 

Resources

TechGenix.com: Basic PowerShell Commands

Take a peek into the basic PowerShell commands for all Windows operating systems.

TechGenix.com: How to Uninstall Software Using PowerShell 

Click here to learn how to uninstall software using PowerShell.

TechGenix.com: Do You Like Your PowerShell Wet or Dry

Read this article to decide if you want a wet or dry PowerShell.

TechGenix.com: Reading Text Files with PowerShell 

Click here to learn how to read text files with PowerShell.

TechGenix.com: Check Your Windows Uptime with PowerShell 

Read this article to learn how to check your Windows uptime with PowerShell.

TechGenix.com: Overview of PowerShell Versions

Learn all about the PowerShell versions here.

Leave a Comment

Your email address will not be published.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Scroll to Top