Home ยป PowerShell Multidimensional Arrays

PowerShell Multidimensional Arrays

In PowerShell, multidimensional arrays are arrays that contain other arrays as elements. These arrays can be organized into multiple dimensions.

There are Jagged arrays and multidimensional arrays in PowerShell.

Jagged Arrays in PowerShell

Jagged arrays are arrays of arrays where each element of the main array can be an array of different lengths. Jagged arrays are useful when you need to represent irregularly shaped data structures.

Here’s an example to create a jagged array involves creating an array of arrays, where each inner array can have a different length.

# Define a jagged array
$jaggedArray = @(
    @(1, 2, 3),
    @(4, 5),
    @(6, 7, 8, 9)

# Access elements of the jagged array
Write-Host "Element at [0,1]: $($jaggedArray[0][1])"  # Output: 2
Write-Host "Element at [1,0]: $($jaggedArray[1][0])"  # Output: 4
Write-Host "Element at [2,2]: $($jaggedArray[2][2])"  # Output: 8

In this example, $jaggedArray is a jagged array with three inner arrays of different lengths. The first inner array has three elements (1, 2, 3), the second has two elements (4,5) and the third has four elements (6,7,8,9).

The output of the above PowerShell script is given below.

Element at [0,1]: 2
Element at [1,0]: 4
Element at [2,2]: 8

Multidimensional Arrays in PowerShell

Multidimensional arrays in PowerShell are arrays that have more than one dimension, allowing you to represent data in a grid-like or tabular format. Multidimensional arrays have a fixed size in each dimension.

Here’s an example of true multidimensional array in PowerShell.

# Define a 2D array
$matrix = @(
    @(1, 2, 3),
    @(4, 5, 6),
    @(7, 8, 9)


In this example, the $matrix is a 3X3 two-dimensional array.



I hope the above article on how to create multidimensional array in PowerShell is helpful to you.

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