ForEach simply looks at a set of list and pulls out one at a time to look at them and then, perform some type of action or set of commands on it.
One different part of a ForEach loop is the keyword in that lives within that parenthetical statement. That tells PowerShell to create a single variable to hold the values that come out, one at a time, for your list.
Let’s define a variable with list of Fruits
$names = “Apple”,”Banana”,”Grape”,”Orange”,”Chiku”
When we make a list within a variable, we have created an array, which is simply a sort of matrix thing that PowerShell holds in memory that lets it store a lots of things at one time.
Let’s also initialize a count variable so we get a feel of how the loop is going.
$count = 0
Let’s use a ForEach loop to count how many names we have. Remember our keyword in we have to create a new variable that we can call FruitName. This holds each single name that comes out of that list of names we have stored in the variable $names.
ForEach ($FruitName in $names)
$count += 1
Finally, I’ll add a simple Write-Host line after the end (after the right curly brace, that is) to display the count, so we can actually give us the count of names in the list of Fruits.
Write-Host “The total number of names is $count.”
Here is the output of above script.
I will come up with more stuffs in my upcoming posts.
Till then keep practicing and stay tuned for more details.