An Introduction to PowerShell – ForEach

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

Write-Host “$FruitName”



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.

Comments are closed.


Most of the contents you find in this blog will be either inherited from MSDN or Navision Developer IT Pro Help. Some places images are also directly taken from these sites. Purpose is simple to try those stuffs and re-produce adding few things as per my understanding to make easy understanding for others and quick reference.

Here nothing under my own brand or authorship of the content. At any point of time we are just promoting Microsoft stuffs nothing personnel with same.

Hope stuffs used here will not violate any copyright agreement with them. In case by mistake or in-intestinally it happens and the Microsoft feels these should not be used Microsoft have full right to inform me about same and will be glad to take down any such content which may be violating the norms.

Purpose is to promote Navision and share with community.

FB Profile

Like FB Page

%d bloggers like this: