23 Adding logic and loops

 

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.

23.1 Foreach and Foreach-Object

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.

Figure 23.1 Diagram of how Foreach works

23.1.1 Foreach

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.

Finally, the script block represented by the curly braces { } will output $a to the screen (figure 23.2).

23.1.2 Foreach-Object

23.1.3 Foreach-Object -Parallel

23.2 While

23.3 Do While

23.4 Lab

23.5 Lab answers