PowerShell: Loop through an Array

Hey there! If you’re starting your PowerShell journey, you might be wondering how to work with arrays. Arrays, essentially collections of items, are pretty common in scripting and automation tasks. Looping through an array is a fundamental concept, and PowerShell includes several methods for iterating or looping through arrays to access and manipulate the items they contain. This guide will provide a beginner-friendly introduction to the main ways to loop through arrays in PowerShell.

How to Loop through an array in PowerShell

Key Takeaways:

  • PowerShell arrays are essential for storing and iterating through collections of items.
  • Understanding the fundamentals of arrays in PowerShell, including their types and initialization, is crucial.
  • The ‘for’, ‘foreach’, and ‘while’ loop constructs offer versatile ways to loop through arrays.
  • Practical examples of array looping showcase how to access, modify, and filter array elements.

What are Arrays in PowerShell?

PowerShell looping through array

Before we dive into the intricacies of array looping in PowerShell, let’s first understand the fundamentals of arrays. An array in PowerShell is a data structure that stores a collection of items under a single variable name. The items, referred to as elements or members, can be strings, integers, custom objects, or even other arrays. Arrays allow you to manipulate a group of related items efficiently. You can loop through arrays to access and work with each element without needing to handle them all individually.

Some common things you may use arrays for in PowerShell include:

  • Storing lists of computer names, usernames, filenames, etc.
  • Grouping data for reports or to export
  • Working with sets of objects returned from commands
  • Gathering related input/output for functions

There are several ways to create arrays in PowerShell:

$array = @("Item1", "Item2", "Item3")
$array = 1..5
$array = Get-ChildItem c:\some\folder
$emptyArray = @() 
$numbers = 1, 2, 3, 4, 5  # Initializing an array with numbers
$fruits = "Apple", "Banana", "Orange"  # Initializing an array with strings

Why Loop Through Arrays in PowerShell?

Looping allows you to iterate through arrays to access each element one after the other for reading and processing. This is important for several reasons:

  • Displaying arrays clearly in the console
  • Exporting or formatting arrays
  • Checking or processing every element
  • Selecting elements that meet certain criteria
  • Updating values or properties
  • Gathering aggregate data like sums, averages, etc.

Without looping, operations you perform on arrays apply only to the whole array object. But by iterating through each element individually, you gain precise control to handle them as needed.

The Different Types of Loops to Iterate through an Array

An array is a collection of values that are stored in a single variable. Each value in the array is assigned a unique index, starting at 0. PowerShell supports arrays of any data type, including strings, numbers, and objects. PowerShell provides several loop constructs, such as ‘for’, ‘foreach’, and ‘while’, that enable you to iterate over array elements and perform specific actions on each item. By mastering these loop constructs, you can manipulate array data efficiently, process large datasets, and enhance the functionality of your PowerShell scripts.

The for loop is used to iterate through a set of values for a specific number of times. The foreach loop is used to iterate through a collection of values, such as an array. The while and do-while loops are used to iterate through a set of values until a specific condition is met.

The ForEach PowerShell Loop

The foreach loop is PowerShell’s most commonly used loop for iterating through an array. It is designed to work with arrays and collections of objects. The ‘foreach’ loop simplifies the process of iterating through arrays by automatically retrieving each element and assigning it to a temporary variable. This eliminates the need for manual indexing and allows for cleaner and more concise code.

The basic syntax for the foreach loop is as follows:

# powershell loop thru array
ForEach ($item in $array) {
    # Code to be executed for each item in the array
}

In this syntax, $array is the name of the array and $item is a variable that is used to represent each item in the array. The code inside the curly braces is the script block executed for each item in the array.

# Loop through an array of strings
$colors = @("Red", "Green", "Blue")

foreach ($color in $colors) {
    Write-Host $color
}

The following example shows how you can iterate through ArrayList in PowerShell:

$arrayList = New-Object System.Collections.ArrayList
$arrayList.Add("Item1")
$arrayList.Add("Item2")
$arrayList.Add("Item3")

foreach ($item in $arrayList) {
    Write-Host $item
}

How to Use the For Loop in PowerShell to Iterate Through an Array?

The for loop is another type of loop that can be used to iterate through an array in PowerShell. Unlike the foreach loop, the for loop is designed to iterate through a set of values a specific number of times. It consists of three essential components: the initialization statement, the condition statement, and the iteration statement.

The basic syntax for the for loop is as follows:

for ($i = 0; $i -lt $array.Length; $i++) {
    # Code to be executed for each item in the array
}

In this syntax, $i is a variable that is used to represent the index of each item in the array. The lt operator is used to compare the value of $i to the length of the array. The code inside the curly braces is executed for each item in the array.

# Loop through an array of numbers
$numbers = @(1, 2, 3, 4, 5)

for ($i = 0; $i -lt $numbers.Length; $i++) {
    Write-Host $numbers[$i]
}

In this example, “$Numbers” is the array containing several numbers. The for loop starts with an initial value of “$i = 0” as a counter, continues as long as “$i” is less than the length of the array $Numbers.Length, and increments “$i” by 1 in each iteration. The code within the loop displays the item at each index using “$Numbers[$i]”.

Here is a real-world example of getting all sub-folder names from a given folder, by iterating through an array:

#Get all SubFolders from the given Folder
$Folders = Get-ChildItem c:\temp -Directory

for ($i = 0; $i -lt $Folders.Length; $i++) {
  Write-Host $Folders[$i].Name
}

The PowerShell Foreach-Object Array Method

In addition to the foreach and for loops, PowerShell also provides the foreach-object (or its alias ForEach statement) method for iterating through an array. This method is similar to the foreach loop, but it is designed to work with pipelines.

The basic syntax for the foreach-object method is as follows:

$array | foreach-object {
    # Code to be executed for each item in the array
}

In this syntax, $array is the name of the array. The foreach-object method is used to iterate through each item in the array. The code inside the curly braces is executed for each item in the array.

Suppose you have a list of servers in a text file (or CSV file) and want to check their status:

# Define the path to the text file
$FilePath = "C:\Scripts\computers.txt"

# Read the contents of the file
$ComputerList = Get-Content $FilePath

# Loop through each computer in the list and ping
$ComputerList | ForEach-Object {
    Write-Host "Pinging $computer..."
    $Result = Test-Connection -ComputerName $_ -Count 1 -ErrorAction SilentlyContinue
    
    if ($result) {
        Write-Host "$_ is reachable." -ForegroundColor Green
    } else {
        Write-Host "$_ is not reachable." -ForegroundColor Red
    }
}

Loop through an Array using While Loop

A While loop in PowerShell is used when you want to repeat a block of code until a specific condition is met. The While loop is similar to the For loop in that it checks a condition before each pass. However, with the While loop, you have more control over when the loop will end, as the increment/decrement section is put inside the loop. Here’s an example of a While loop that prints all the elements of an array.

$Array = @("Chocolate","Strawberry","Vanilla","Pistachio","Coffee")
$index=0

While($i -lt $Array.count){
    Write-host $Array[$index]
    $index++
}

In this example, the loop continues iterating as long as the condition $index -lt $array.Length is true. Inside the loop, we can perform actions on each element of the array using the index $index. The value of $index is incremented after each iteration.

The Do-While Loop to Loop through Array

The Do-While loop is another type of loop that’s similar to the While loop. However, the Do-While loop executes the code block at least once, regardless of the initial condition. The Do-While loop continues to execute the code block until the condition is false. The break statement is used to terminate the loop before the condition is met. Here’s an example of the Do-While loop that prints all the elements of an array.

$Array = @("John","Mary","Kate","Tom")
$i=0

Do {
    Write-host $Array[$i++]
}
While($i -lt $Array.length)

In this example, the loop first executes the loop body and then checks the condition for array length “$i -lt $Array.length”. If the condition is true, the loop continues iterating; otherwise, it terminates.

This can be useful to guarantee the loop runs at least once before checking a condition.

Looping Through an Array of Objects in PowerShell

PowerShell supports arrays of objects, which can be used to store complex data structures. To iterate through an array of objects, you can use the foreach loop or the foreach-object method.

#Define an object array
$users = @(
    @{ Name = "John"; Age = 30 },
    @{ Name = "Jane"; Age = 25 },
    @{ Name = "Bob"; Age = 40 }
)

#Loop through array and get object properties
foreach ($user in $users) {
    Write-Host $user.Name
}

In this example, $users is an array of objects that contains the name and age of three users. The foreach method is used to iterate through each user in the array and display their name using the Write-Host cmdlet.

Looping Through an Array of Strings in PowerShell

PowerShell also supports a string array, which can be used to store simple data structures. To iterate through an array of strings, you can use the foreach loop or the foreach-object cmdlet.

$fruits = "Apple", "Banana", "Cherry"

$fruits | ForEach-Object { Write-Output $_ }

In the above example, $fruits is an array of strings that contains the names of three fruits. The foreach-object loop is used to pipe the collection, iterate through each color in the array, and display its name using the Write-Output cmdlet.

Tips for Optimizing Your PowerShell Loops

When working with loops in PowerShell, there are several tips that you can follow to optimize your code:

  1. Use the foreach loop for arrays and collections of objects.
  2. Use the for loop for arrays of simple data types, such as strings and numbers.
  3. Avoid using the while and do-while loops unless you need to iterate through a set of values until a specific condition is met.
  4. Use the foreach-object method for pipelines and complex data structures.

Index of the Current Item in the Loop

You can use the index of the current item in the loop by using the $index variable. For example, you could print the index and item for each item in the array using the following code:

$Array = @("Chocolate","Strawberry","Vanilla","Pistachio","Coffee")
$index=0

foreach ($index in 0..($Array.Length - 1)) {
     Write-Host "$index : $($Array[$index])"
 }

Filter Array Elements:

PowerShell loop structures provide an effective mechanism to filter array elements based on defined criteria. The Where-Object cmdlet can filter an array based on a condition. For example, you could loop through an array of numbers and print only the even ones using the following code:

 foreach ($num in (1..10 | Where-Object { $_ % 2 -eq 0 })) {
     Write-Host $num
 }

You can also filter the array values with an “IF” statement:

#Number Array
$Numbers = 1, 2, 3, 4, 5, 6

#Iterate through the array and filter
$EvenNumbers = foreach ($Number in $Numbers) {
    if ($number % 2 -eq 0) {
        $number
    }
}
#Get Even Numbers
$EvenNumbers

In this example, we use a foreach loop to iterate through each element in the array. By applying the if condition and modulus operator (%), we filter out the numbers that are not divisible by 2. The filtered even numbers are then stored in the $evenNumbers array. Here is another real-world example of filtering items from an entire collection:

#Get All Files from given folder
$Files = Get-ChildItem -Path "C:\Temp" -File

Foreach ($File in $Files) 
{ 
    If ($file.Length -gt 100KB) { 
        Write-Host $file.FullName 
    } 
}

In the above example, The Get-ChildItem cmdlet gets all files from a given folder; The If condition filters the files based on their size.

Break Out of a Loop

You can use the break keyword to stop iterating during a for loop. Let’s say you have an array of numbers, and you want to iterate through them, but break out of the loop if a specific condition is met, such as encountering a specific number.

$array = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

foreach ($item in $array) {
    Write-Host "Checking item: $item"

    # Break the loop if the item is 5
    if ($item -eq 5) {
        Write-Host "Found item 5, breaking the loop."
        break
    }
}

Conclusion

In summary, looping through arrays is a common task in PowerShell that can be accomplished using a variety of loops and methods. Looping through arrays is essential to access elements for display, checking, aggregation, export, and other key tasks in Windows PowerShell. While the four loops presented in this article are not the only ones that you can use in PowerShell, they are among the most common and versatile. Choose the loop type that best suits your requirements and the specific task you want to accomplish with the array elements. By using the right loop for the job, you can significantly reduce code complexity and speed up array processing times.

Further Reading:

What is array looping in PowerShell?

Array looping in PowerShell refers to the process of iterating through each element in an array and performing actions on them. It allows you to process and manipulate collections of data efficiently.

What are the different types of arrays in PowerShell?

There are different types of arrays in PowerShell, including scalar arrays, mixed arrays, and ArrayLists. Scalar arrays store a single data type, mixed arrays can store different data types, and ArrayLists provide dynamic resizing and additional methods.

How do you initialize and modify arrays in PowerShell?

You can initialize an array in PowerShell by assigning values to it or by using the `@()` syntax. To add elements to an array, you can use the `+=` operator or the `Add()` method. Arrays can be resized using the `Redim` statement.

What are the ‘while’ and ‘do-while’ loops in PowerShell?

The ‘while’ and ‘do-while’ loops in PowerShell are conditional looping constructs. The ‘while’ loop executes a block of code as long as a specified condition is true, and the ‘do-while’ loop executes the code at least once and then continues execution as long as the condition is true.

How can I access and modify array elements in PowerShell?

In PowerShell, you can access array elements by using their index. To modify an array element, you can assign a new value to it using the index. For example, `$array[0] = “New Value”`.

How do I choose the right loop for a task in PowerShell?

To choose the right loop for a task in PowerShell, consider factors like performance, readability, and code elegance. ‘For’ loops are suitable for precise control, ‘foreach’ loops simplify iteration, and ‘while’ loops work well for conditional iteration.

How do you retrieve items from an array in PowerShell?

To retrieve items from an array in PowerShell, you can access them by their index. Arrays in PowerShell are zero-indexed, meaning the first item is at index 0, the second item at index 1, and so on. Here’s a simple example:
$array = @("apple", "banana", "cherry")
# Access the first item
$firstItem = $array[0] # Returns "apple"
# Access the second item
$secondItem = $array[1] # Returns "banana"
# Access the third item
$thirdItem = $array[2] # Returns "cherry"

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

One thought on “PowerShell: Loop through an Array

  • Be careful when using “continue” to go to the next iteration in a “foreach”. This may give unwanted results like silently aborting the whole script.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *