Unless you have some prior programming experience, starting to learn scripting can be a bit daunting at times. One of the key concepts to understand in my opinion, is a foreach loop. This not something that is particular to PowerShell, as you will find foreach loops in every programming language. As I laid in bed last night getting kicked by my one-year-old my mind ventured into how to explain a foreach loop very simply. This is what I came up with…

Concept

Imagine you are sitting at a table with ten individually wrapped Reese’s Peanut Butter cups. You decide “Hey, I want to eat all of these right now, one by one”. How would you go about this? You would simply take each Reese’s, open up the package, take off that damned annoyed black wrapper thing that it comes with, and then proceed to shovel it into your mouth whole until all the Reese’s are gone. At least that’s what I do. Essentially what you just did was a real-world foreach loop.

In a foreach loop, you have a collection of things and you want to go through each one and do something. That is it in a nutshell.

PowerShell Example

If we were to take our real-world example and put it into some PowerShell code, it may look something like this:

# Our collection of Reese's $ReesesCollection = 'Reeses-1','Reeses-2','Reeses-3','Reeses-4', 'Reeses-5','Reeses-6','Reeses-7','Reeses-8','Reeses-9','Reeses-10' # For each Reeses, do this foreach ($Reeses in $ReesesCollection) { Remove-Wrapper -Name $Reeses Remove-BlackThingy -Name $Reeses Add-Reeses -Name $Reeses } 1 2 3 4 5 6 7 8 9 10 # Our collection of Reese's $ ReesesCollection = 'Reeses-1' , 'Reeses-2' , 'Reeses-3' , 'Reeses-4' , 'Reeses-5' , 'Reeses-6' , 'Reeses-7' , 'Reeses-8' , 'Reeses-9' , 'Reeses-10' # For each Reeses, do this foreach ( $ Reeses in $ ReesesCollection ) { Remove - Wrapper - Name $ Reeses Remove - BlackThingy - Name $ Reeses Add - Reeses - Name $ Reeses }

Here, we have our collection of ten Reese’s cups in a variable – $ReesesCollection. We will use a foreach loop to go through each one and run these faux PowerShell commands – Remove-Wrapper, Remove-BlackThingy and Add-Reeses which are the steps to take of actually consuming them.

Notice that in our code, each command uses $Reeses as the thing to perform its action on. This $Reeses variable is sort of a placeholder for each Reese’s in our $ReesesCollection. The name actually does not matter at all. I could use foreach ($Thing in $ReesesCollection) and it would still work, as long as I am still using $Thing in my foreach block with my faux PowerShell commands. So if our code used real commands, it would cycle through the $ReesesCollection and complete.

Welp, I am hungry. After writing this post I want to go devour ten Reese’s cups and its only 8:50 AM.