Skip to content

How to use Foreach in PowerShell

Jordan Hammond fun headshot
Jordan Hammond|Updated October 9, 2025
How to Use Foreach in PowerShell
How to Use Foreach in PowerShell

Foreach in PowerShell runs a block of code once for every item in a collection. There are three common forms — the ForEach-Object cmdlet (pipeline), the foreach keyword (language construct), and the foreach method on collections — and each has different performance and memory tradeoffs you should know.

Now that we have the editor-pleasing succinct definition to start this off, we can dive into what that means.

ConnectIcon CTA

Easily run PowerShell scripts on remote devices

Need to run your awesome PowerShell scripts on remote devices? PDQ Connect can easily execute PowerShell scripts on any managed device with an active internet connection. 

What are foreach options in PowerShell?

What is Foreach-Object, and when should I use it?

Foreach-Object is a pipeline cmdlet that processes items as they flow through the pipeline. It is memory-friendly because it streams items (it does not require the entire collection to be realized first), but per-item cmdlet overhead can make tight loops slower than in-memory alternatives.

Part of what makes Foreach-Object confusing is it has an alias of foreach, so it may also be confused for the keyword. Watch for the pipe (|) — that signals pipeline usage. Only the cmdlet is going to allow data in through the pipe. While slower, it comes with the ability to pass the results into another command.

What is foreach keyword, and when should I use it?

Foreach keyword loads all items into memory and then runs. This is usually significantly faster as long as you have the required memory to run it because it avoids pipeline overhead. If the collection expression returns a fully realized array, foreach will iterate that array; but for very large data sets, confirm memory usage before choosing this pattern.

Foreach keyword is my usual go-to; I love the speed, and I rarely deal with data sets so large my memory could become an issue.

What is foreach method, and when should I use it?

Foreach method came around in PowerShell 4 and is surprisingly difficult to find information about. If you run Get-Member for a collection, it won’t even mention foreach as a method.

What makes it stand out is speed: Unlike the ForEach-Object cmdlet, .ForEach() runs in-process on the collection, avoiding pipeline overhead. This makes it one of the fastest ways to perform bulk operations. If you need to terminate a bunch of processes at once or quickly convert data types across a collection, .ForEach() can get the job done efficiently.

How can I use foreach for data cleanup?

It is uncommon for the data you collected to be exactly what you wanted, whether you need to convert bits of information to something new or remove all items from your collection that don’t meet the parameters you are looking for. Let's say you are given a CSV file of action heroes; if we read that list, it looks like this:

Table of fictional movie characters listing first name, last name, kills, and number of movies, including John Rambo with 490 kills across 5 films, John Wick with 299 kills across 3 films, and others.

That is an awesome list, and whoever had this idea is probably pretty cool. But what if we don’t need everything from it? This is where we can use foreach. In this first example, we will trim this list down to only include action heroes named John.

$ActionHero = Import-CSV "C:\Temp\john.csv" $FinalList = New-Object 'System.Collections.ArrayList' foreach($Hero in $ActionHero){    If($Hero.FirstName -eq "John"){         $FinalList.Add($Hero) > $null    } }

This option takes each hero named John and builds a new collection that looks like this.

Filtered table showing only characters named John, including Rambo, Wick, Matrix, McClane, and Preston, with their kills and number of movies.

We can take that array and build a new CSV with only the data we want. Having PowerShell there to clean up old or junk data and whittling it down to what is relevant is very valuable for creating colorful charts and graphs that management can "ooh" and "aah" over, making you look like a rock star.

How can I use foreach to run commands?

More than just cleaning up data, foreach can also be used to run a series of commands against many items in short order.

Let’s say I have been fired because I made one too many snide remarks against management in my blogs. I have been right about management this entire time, so instead of service accounts or LAPS, we have a local admin account that has the same name and password on each server. Who knows what evil deeds I could do if I so desired. With foreach, we can grab every computer and reset the password.

$computers = Get-ADComputer -filter * | Select-Object DNSHostname $cred = Get-Credential foreach($computer in $computers){     $LocalAdmin = [ADSI] "WinNT://$computer/LocalAdminGuy"     $LocalAdmin.SetPassword($cred.GetNetworkCredential().password) }

Now, every machine has a new local admin. While we are concerned about this, I would maybe suggest disabling that account and implementing LAPS … or I would if I had not been let go mid-blog!

What is the best foreach option in PowerShell?

The best foreach option depends on your scenario: Use ForEach-Object for streaming pipeline data, the foreach keyword for fast in-memory loops, and .ForEach() for the fastest in-process operations on arrays/lists already in memory. Always test on representative data and use managed credential solutions for bulk administrative tasks.

Now go forth and collect all the data your executive has been telling you they needed last week … so they can ignore it for a month and ask for it again when they forget you already sent it. It is the corporate way!

Jordan Hammond fun headshot
Jordan Hammond

Jordan had spent his life wondering why tasks he didn’t like to do had no options to complete themselves. Eventually he had to make that happen on his own. It turned out that he enjoyed making tasks complete themselves, and PDQ thought that is something he should talk about on the internet.

Related articles