How to Create an Array of Arrays in PowerShell (With Example)


Often you may want to create an array of arrays in PowerShell.

You can use the following methods to do so:

Method 1: Create Array of Arrays

$my_array = @(
    @(1, 2, 3, 4, 5),
    @(6, 7, 8, 9, 10),
    @(11, 12, 13, 14, 15)
)

This particular example creates an array named $my_array that contains three arrays inside it.

Method 2: Create Array of Arrays (With Only One Array in List)

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

In the rare scenario where you only have one array inside of another array, you must use a comma in front of the inner array to force the object to be an array within an array.

The following examples show how to use each of these methods in practice.

Example 1: How to Create Array of Arrays

We can use the following syntax to create an array named $my_array that contains three arrays inside it:

$my_array = @(
    @(1, 2, 3, 4, 5),
    @(6, 7, 8, 9, 10),
    @(11, 12, 13, 14, 15)
)

We can then use bracket notation to retrieve specific elements from specific arrays.

For example, we can use the following syntax to retrieve the fourth element from the second array:

$my_array[1][3]

The following screenshot shows how to use this syntax in practice:

PowerShell create array of arrays

Notice that this returns the value 9, which represents the value in the fourth position of the second array.

Example 2: How to Create Array of Arrays (With Only One Array in List)

We can use the following syntax to create an array named $my_array that contains only one array inside it:

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

We can then use bracket notation to retrieve specific elements from the inner array.

For example, we can use the following syntax to retrieve the fourth element from the inner array:

$my_array[0][3]

The following screenshot shows how to use this syntax in practice:

PowerShell create array of arrays with only one array in list

Notice that this returns the value 4, which represents the value in the fourth position of the inner array.

Note: If you do not include a comma when defining the inner array, then PowerShell will simply create a one-dimensional array instead.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Compare Two Arrays
PowerShell: How to Check if Input Value Exists in Array
PowerShell: How to Remove Duplicate Values from Array
PowerShell: Check if String Exists in List of Strings

Leave a Reply