PowerShell Multidimensional Arrays

Rohan Timalsina Feb 15, 2022
  1. Create Arrays in PowerShell
  2. Create Multidimensional Arrays in PowerShell
PowerShell Multidimensional Arrays

A data structure called array is a collection of elements of the same or various data types. PowerShell supports arrays having one or multiple dimensions.

A multidimensional array contains multiple dimensions, and each row of a dimension has the same number of elements. The elements in a multidimensional array are stored in row-major order.

For example, in 2-dimensional array, the elements are stored as [0,0], [0,1], [1,0], [1,1]. This article will teach you to create a multidimensional array in PowerShell.

Create Arrays in PowerShell

You can create an empty array by using @(). You can insert values in the @() parentheses to store them in an array.

$data = @()

The following command creates an array $fruits with 3 elements. The array’s length is fixed, and it cannot be changed.

$fruits = @('Apple', 'Banana', 'Mango')



Although @() is the proper syntax, you can use comma-separated lists like this to create an array.

$fruits = 'Apple', 'Banana', 'Mango'

Create Multidimensional Arrays in PowerShell

The above array is a 1-dimensional array. It means you can access its elements by using type[] as the following example.




But, a 2-dimensional array has a comma inside type[,]. The elements in a 2-dimensional array, $sub can be accessed by using $sub[0,0], $sub[0,1], $sub[0,2], $sub[1,0], $sub[1,1], $sub[1,2], and so on.

Let’s see an example to create a 2-D array of length 4.

$sub = New-Object 'object[,]' 2, 2
$sub[0, 0] = 'science'
$sub[0, 1] = 'maths'
$sub[1, 0] = 'english'
$sub[1, 1] = 'computer'

Call the $sub variable to view the elements:




To get an individual element:

$sub[1, 1]



A 3-dimensional array has a data type type[,,], a 4-dimensional array has a data type type[,,,] and so on. You can quickly build multidimensional arrays in PowerShell by utilizing the above method.

Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website

Related Article - PowerShell Array