Home ยป PowerShell Array of Arrays: A Complete Guide

PowerShell Array of Arrays: A Complete Guide

In PowerShell, an array is a fundamental data structure used to store a collection of items. But what if you need to store a collection of arrays? That’s where “arrays of arrays,” also known as nested arrays or multidimensional arrays.

This guide will provide an overview of arrays of arrays in PowerShell, covering how to create them, access elements, iterate through them, and explore practical examples of their usage.

What is an Array of Arrays in PowerShell?

An array of arrays is a collection where each element is an array. You can visualize this as a table with rows and columns, where each row is an array, and the table is the array holding these rows.

Creating an Array of Arrays

There are several ways to create an array of arrays in PowerShell:

a) Method 1: Using the Comma Operator

The simplest way is to use the comma operator to define each inner array and enclose them within parentheses:

$myArrayOfArrays = (
    (1, 2, 3),
    (4, 5, 6),
    (7, 8, 9)
)
PS C:\Users\ShellAdmin> $myArrayOfArrays
1
2
3
4
5
6
7
8
9

b) Method 2: Using @() for Empty Arrays and Adding Elements

You can initialize an empty array and then add arrays to it:

$myArrayOfArrays = @()
$myArrayOfArrays += ,@(1, 2, 3)  # Note the unary comma operator
$myArrayOfArrays += ,@(4, 5, 6)
PS C:\Users\ShellAdmin> $myArrayOfArrays
1
2
3
4
5
6

c) Creating Jagged Arrays

Jagged arrays are arrays of arrays where the inner arrays can have different lengths:

$jaggedArray = (
    (1, 2),
    (3, 4, 5, 6),
    (7, 8, 9)
)
PS C:\Users\ShellAdmin> $jaggedArray
1
2
3
4
5
6
7
8
9

Accessing Elements in a PowerShell Array of Arrays

You access elements in a nested array using their indices.

Note: PowerShell arrays are zero-indexed (the first element is at index 0).

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

# Access the first element of the first inner array
$firstElement = $myArrayOfArrays[0][0]  # $firstElement will be 1

# Access the third element of the second inner array
$anotherElement = $myArrayOfArrays[1][2] # $anotherElement will be 6
PS C:\Users\ShellAdmin> $firstElement
1

PS C:\Users\ShellAdmin> $anotherElement
6

Iterating Through Nested Arrays

You can use nested loops to process each element in an array of arrays.

a) Using Nested foreach Loops:

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

foreach ($innerArray in $myArrayOfArrays) {
    foreach ($element in $innerArray) {
        Write-Host "Element: $element"
    }
}
Element: 1
Element: 2
Element: 3
Element: 4
Element: 5
Element: 6
Element: 7
Element: 8
Element: 9

b) Using Nested for Loops:

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

for ($i = 0; $i -lt $myArrayOfArrays.Length; $i++) {
    for ($j = 0; $j -lt $myArrayOfArrays[$i].Length; $j++) {
        Write-Host "Element at [$i][$j]: $($myArrayOfArrays[$i][$j])"
    }
}
Element at [0][0]: 1
Element at [0][1]: 2
Element at [0][2]: 3
Element at [1][0]: 4
Element at [1][1]: 5
Element at [1][2]: 6
Element at [2][0]: 7
Element at [2][1]: 8
Element at [2][2]: 9

Practical Examples

a) Example 1: Storing Tabular Data

Arrays of arrays are perfect for representing tables:

$products = (
    ("Product", "Price", "Quantity"),
    ("Laptop", 1000, 10),
    ("Mouse", 50, 10),
    ("Keyboard", 70, 10)
)
PS C:\Users\ShellAdmin> $products
Product
Price
Quantity
Laptop
1000
10
Mouse
50
10
Keyboard
70
10

b) Example 2: Working with Hierarchical Data

Arrays of arrays can model hierarchical structures:

$fileSystem = (
    ("C:\",
        ("Users",
            ("Adam", "Documents", "Pictures"),
            ("Andrew", "Documents")
        ),
        ("Program Files",
            ("App1", "docker", "my-app"),
            ("App2", "data")
        )
    )
)
PS C:\Users\ShellAdmin> $fileSystem
C:\
Users


Length         : 3
LongLength     : 3
Rank           : 1
SyncRoot       : {Adam, Documents, Pictures}
IsReadOnly     : False
IsFixedSize    : True
IsSynchronized : False
Count          : 3

Length         : 2
LongLength     : 2
Rank           : 1
SyncRoot       : {Andrew, Documents}
IsReadOnly     : False
IsFixedSize    : True
IsSynchronized : False
Count          : 2

Program Files
Length         : 3
LongLength     : 3
Rank           : 1
SyncRoot       : {App1, docker, my-app}
IsReadOnly     : False
IsFixedSize    : True
IsSynchronized : False
Count          : 3

Length         : 2
LongLength     : 2
Rank           : 1
SyncRoot       : {App2, data}
IsReadOnly     : False
IsFixedSize    : True
IsSynchronized : False
Count          : 2

Multidimensional Arrays vs. Jagged Arrays

Understanding the difference between Multidimensional Arrays and Jagged Arrays can help you choose the right structure for your data.

  1. Multidimensional Arrays
    • These are fixed-size arrays where all rows have the same number of columns.
    • They resemble a strict table or matrix format.
  2. Jagged Arrays
    • These are more flexible, allowing rows (inner arrays) to have varying lengths.
    • A jagged array is an array of arrays, ideal for representing non-uniform data.

Choose multidimensional arrays for structured data like grids or matrices, and jagged arrays for datasets with irregular row sizes.

Adding Elements to an Existing Array of Arrays

To add an element to an inner array:

$myArrayOfArrays = (
    (1, 2, 3),
    (4, 5, 6)
)

$myArrayOfArrays[0] += 7 # Adds 7 to the first inner array
PS C:\Users\ShellAdmin> $myArrayOfArrays
1
2
3
7
4
5
6

To add a new array to the outer array:

$myArrayOfArrays = (
    (1, 2, 3),
    (4, 5, 6)
)
$myArrayOfArrays += ,@(7, 8, 9) # Adds a new inner array (7, 8, 9)
PS C:\Users\ShellAdmin> $myArrayOfArrays
1
2
3
4
5
6
7
8
9

Conclusion

Arrays of arrays, or nested arrays, are a powerful way to organize and manage complex data in PowerShell.

Understanding how to create, access, and manipulate them is essential for many scripting and automation tasks.

You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.