Part II of Using Loops in PowerShell. In this tutorial, you will learn how to use foreach loops in PowerShell.

Setup

If you have not already done so, click open Windows PowerShell ISE.
If you’re ever in the market for some great Windows web hosting, try Server Intellect. We have been very pleased with their services and most importantly, technical support.

Step one.

The foreach loop, closely related to the for-loop, also executes for a defined number of times. The difference between the two however, is that it does not have to be told how to increment its values. Once you give foreach a collection of objects and the variable name for the iterator, it will automatically loop through each item in the collection one by one.
The foreach loop is written like the example below:
Code Block
PowerShell Script
foreach ($i in Get-Alias)

{

                Write-Host $i.name

}
Upon running the code, the output pane will appear as follows:
This is actually a shortened list of the output, for there are many AliasInfo objects within the specified collection.

Step two.

Within the parenthesis, $i in Get-Alias, is where the iterator is defined. In this case, variable “$i” is called. One tells the iterator what collection of items it is to point to, which in this example is Get-Alias, so it returns a collection of AliasInfo objects that defines the aliases currently defined within the system.
For each repetition of the loop, $i refers to one of these objects; you can then reference anything from these objects within the loop body. The loop simply displays the name of the alias in the example above.

A Few Last Words…

In the case where you are going through a collection of objects, the foreach loop is ideal. Join us next time for additional Windows PowerShell tutorials! Till then…
We stand behind Server Intellect and their support team. They offer dedicated servers, and they are now offering cloud hosting!