Autocodewizard Logo Loops and Iteration - Autocodewizard Ebooks - PowerShell Essentials: Mastering Scripting and Automation for Windows Administration

Chapter 5: Loops and Iteration

Learn about loops in PowerShell, including for, foreach, and while loops, to automate repetitive tasks and iterate over collections of data.

Loops are essential for automating repetitive tasks and processing collections of data. PowerShell offers several types of loops�for, foreach, and while�each suited to different use cases. In this chapter, we�ll explore how to use these loops effectively in PowerShell scripts.

The For Loop

The for loop is commonly used for a known number of iterations. It consists of three parts: initialization, condition, and increment. Here�s the structure of a for loop:

for ($i = 0; $i -lt 5; $i++) {
    Write-Output "Iteration $i"
}

In this example, $i is initialized to 0. The loop continues while $i is less than 5, and $i is incremented by 1 after each iteration. This loop will output �Iteration 0� to �Iteration 4.�

The Foreach Loop

The foreach loop is ideal for iterating over each item in a collection, such as an array or list. This loop processes each element individually:

$numbers = @(1, 2, 3, 4, 5)

foreach ($number in $numbers) {
    Write-Output "Number: $number"
}

In this example, foreach processes each item in the $numbers array, outputting each number one by one.

The While Loop

The while loop continues executing as long as its condition evaluates to $true. This loop is useful when the number of iterations is unknown:

$count = 0

while ($count -lt 5) {
    Write-Output "Count is $count"
    $count++
}

In this example, the loop will execute until $count reaches 5, incrementing $count by 1 after each iteration.

The Do-While Loop

The do-while loop is similar to the while loop, but it guarantees at least one iteration because the condition is evaluated at the end of each loop:

$count = 0

do {
    Write-Output "Count is $count"
    $count++
} while ($count -lt 5)

In this example, the loop will execute once even if $count is greater than or equal to 5 initially. This is useful when an action must be performed at least once.

Using Break and Continue

The break and continue statements control the flow of loops:

For example, using break and continue in a for loop:

for ($i = 0; $i -lt 10; $i++) {
    if ($i -eq 5) { break }
    if ($i % 2 -eq 0) { continue }
    Write-Output "Odd number: $i"
}

This loop outputs only odd numbers and stops once $i reaches 5.

Looping Through a Hashtable with Foreach

You can also use the foreach loop to iterate over key-value pairs in a hashtable. This is useful for managing collections of related data:

$person = @{
    Name = "Alice"
    Age = 30
    Department = "Sales"
}

foreach ($key in $person.Keys) {
    Write-Output "$key: $($person[$key])"
}

In this example, foreach iterates over each key in the hashtable, printing the key and its corresponding value.

Nesting Loops in PowerShell

Loops can be nested within each other to handle complex data structures. This is helpful for iterating over multidimensional arrays or performing actions that depend on multiple conditions:

$matrix = @(
    @(1, 2, 3)
    @(4, 5, 6)
    @(7, 8, 9)
)

foreach ($row in $matrix) {
    foreach ($item in $row) {
        Write-Output $item
    }
}

This code iterates over each row in the matrix and then over each item within each row, outputting each item individually.

Summary and Next Steps

In this chapter, we covered the for, foreach, while, and do-while loops in PowerShell, as well as useful control statements like break and continue. Understanding how to use loops will help you automate repetitive tasks and process data efficiently. In the next chapter, we�ll explore functions and modular code, which are essential for organizing and reusing your PowerShell scripts.