For Each Loop
Server Academy Members Only
Sorry, this lesson is only available to Server Academy Full Access members. Upgrade your plan to get instant access to this and many more premium courses. Click the Upgrade Plan button below to get started.

Saving Progress...
In this lecture, we are going to discuss PowerShell For Each loop.

Open the PowerShell ISE as an Administrator.

We are going to go ahead and start by discussing what a For Each Loop is.
Now, this is a loop that is specifically made to iterate over elements stored inside of an array.
So, we take our array: $Vehicles = @(“Cars”,”Motorcycles”,”Trucks”,”SUVs”) and we execute it in PowerShell.
Type in $Vehicles and press Enter. We get the entire array of contents.

Now, if we want to iterate that through a For Loop we can type and execute the following:
$Vehicles = @(“Cars”,”Motorcycles”,”Trucks”,”SUVs”)
for ($i=0; $i -lt $Vehicles.Count; $i++) {
$Vehicles [$i]
}
Basically, it will show the same output as before but now in a For Loop.

We can further modify that and add the following to the script.
$Vehicles = @(“Cars”,”Motorcycles”,”Trucks”,”SUVs”)
for ($i=0; $i -lt $Vehicles.Count; $i++) {
echo (“Element $i = “ + $Vehicles [$i])
}
Execute the script.

This is the way we would have done it before.
Now, inside of a For Loop or a For Each loop rather we can do things like this:
$Array = @(“Element1”,”Element2”)
ForEach($Element in $Array) {
$Element
}
Execute the script.

What we are doing here is assign a variable $Element, and this $Element represents whatever element we are actually iterating over currently inside the array and we can change the $Element to any value like $i and will output the same results.

Now, if we are trying to make something like a new user account we can do an array that contains a list of people like the following:
$People = @(“Paul Hill”,”Jason Tolber”,”Charlie Irkins”,”Malanie Garth”)
ForEach ($Person in $People) {
echo “Creating new Active Directory user account for $Person”
}
Let’s execute the script.

You can see that it is creating a new Active Directory User Account for the users.
So, this is an example, we can actually directly write a new command to our script like using the New-ADUser and Import the Active Directory module to actually create a user. But you can actually create an Active Directory account by using arrays in the For Each loop.
So, that is an example of what a For Each Loop is and this is how you can use it. Of course, we are just echoing an output, we are not actually creating anything but just as an example this is how you would do it.
Server Academy Members Only
Want to access this lesson? Just sign up for a free Server Academy account and you'll be on your way. Already have an account? Click the Sign Up Free button to get started..