Looping (or going through a list of objects one at a time) is a fundamental concept in any language, and PowerShell is no exception. There will come a time when you will need to execute a block of code numerous times. PowerShell is well equipped to handle this for you.
This section may be a bit confusing, as there is a difference between Foreach and Foreach-Object. Take a look at figure 23.1 for a visual representation of how Foreach works.
Probably the most common form of looping is the Foreach command. Foreach allows you to iterate through a series of values in a collection of items, such as an array. The syntax of a Foreach command is
Foreach (p temporary variable IN collection object) {Do Something}
The process block (the part surrounded by {} ) will execute as many times as the number of collection objects. Let’s look at the following command and break it down:
PS C:\Scripts> $array = 1..10 PS C:\Scripts> foreach ($a in $array) {Write-output $a}
First, we made a variable called $array that will contain an array of numbers from 1 to 10. Next, we are making a temporary variable ($a) and assigning it to the current item in the collection that we are working with. The variable is available only inside the script block and will change as we iterate through the array.