The PowerShell foreach loop allows you to iterate over collections. Let's dive into how it works.

There comes a time when using PowerShell that you've got more than one object to manage. Whether you're getting the contents of a directory with Get-ChildItem, checking up on some Active Directory computers with Get-AdComputer or finding something in WMI with Get-WmiObject you've got multiple objects.

To manage multiple objects at once you've got to have a way to see all of them. �This is where the PowerShell loop comes in.

PowerShell has a few different types of loops. �Today, I'd like to discuss the foreach loop.

The foreach loop is the most common loop I use. I find that it's the easiest to remember and it just works.

Technically, it might not be the fastest way to go through a collection of objects but for the large majority of the small scripts I write it works well.

Let's go over an example.

I have a directory of text files that I'd like to merge into one big text file. �To do this, I have to look at each file, get its contents and finally merge them all into a single file.

If you find yourself saying words like each and for every it's very likely you're going to need a loop; probably a foreach loop.

## Put all files in the C:DirectoryWithFiles into the $files variable
$files = Get-ChildItem C:DirectoryWithFiles -File
## Create a blank file to merge all other files into
Add-Content -Path merged_file.txt -Value ''
## Start looking at each file
foreach ($file in $files) {
    ## Get the contents of each file and append it to merged_file.txt
    Add-Content -Value (Get-Content $file.FullName) -Path merged_file.txt
}

If you now check out merged_file.txt you'll notice that it has merged the contents of each of the files in C:\DirectoryWithFiles into our single file. Pretty cool, huh?

This is just a single instance of when you'd use a foreach �loop. PowerShell's library of cmdlets, constructs, functions, etc is vast and there's always a better way to do things. If you know of a better way to accomplish this task please comment below.

Join the Jar Tippers on Patreon

It takes a lot of time to write detailed blog posts like this one. In a single-income family, this blog is one way I depend on to keep the lights on. I'd be eternally grateful if you could become a Patreon patron today!

Become a Patron!