Kae Travis

Using the PowerShell For Loop

Tags:

One of the essential looping constructs in PowerShell is the “For” loop. In this blog post, we’ll delve into using the PowerShell For loop, its syntax, and how we can utilise it effectively in our scripts.

Understanding the For Loop

The For loop in PowerShell is a powerful mechanism that allows us to iterate over a sequence of values and execute a set of statements for each value. It is particularly useful for performing tasks that require a specific number of iterations or when working with a known range of values.

Syntax of the For Loop

The syntax of the For loop in PowerShell consists of three parts:


    for ($Initialisation; $Condition; $Increment) {
        # Code to execute for each iteration
    }
    

In this structure, the three parts are as follows:

  • Initialisation: Here, we set an initial value for a variable, typically used as a counter.
  • Condition: The loop will continue executing as long as this condition is true.
  • Increment: After each iteration, the value in the variable is modified according to this expression.

The code block within the loop contains the statements to execute during each iteration.

PowerShell For Loop Examples

Let’s explore a couple of practical examples to demonstrate the usage of the For loop in PowerShell:

Example 1: Counting from 1 to 5

for ($i = 1; $i -le 5; $i++) {
	Write-Host "Number $i"
}

In this example, we initialise the variable $i to 1 and increment it by 1 in each iteration. The loop continues until $i is less than or equal to 5, and we print the iteration number.

Example 2: Iterating Through an Array

$colors = @("Red", "Green", "Blue", "Yellow", "Orange")

for ($i = 0; $i -lt $colors.Length; $i++) {
	Write-Host "The colour is: $($colors[$i])"
}

In this example, we use the For loop to iterate through a string array of colours. The loop initialises $i to 0 and iterates while $i is less than the length of the array. We print each colour element to screen.

The For loop is a valuable tool in PowerShell for handling repetitive tasks and iterating through known sequences of values.

Using the PowerShell For Loop
Using the PowerShell For Loop

Leave a Reply