Welcome PowerShell User! This recipe is just one of the hundreds of useful resources contained in the PowerShell Cookbook.

If you own the book already, login here to get free, online, searchable access to the entire book's content.

If not, the Windows PowerShell Cookbook is available at Amazon, or any of your other favourite book retailers. If you want to see what the PowerShell Cookbook has to offer, enjoy this free 90 page e-book sample: "The Windows PowerShell Interactive Shell".

7.2 Create a Jagged or Multidimensional Array

Problem

You want to create an array of arrays or an array of multiple dimensions.

Solution

To create an array of arrays (a jagged array), use the @() array syntax:

PS > $jagged = @(
      (1,2,3,4),
      (5,6,7,8)
   )

PS > $jagged[0][1]
2
PS > $jagged[1][3]
8

To create a (nonjagged) multidimensional array, use the New-Object cmdlet:

PS > $multidimensional = New-Object "int32[,]" 2,4
PS > $multidimensional[0,1] = 2
PS > $multidimensional[1,3] = 8
PS >
PS > $multidimensional[0,1]
2
PS > $multidimensional[1,3]
8

Discussion

Jagged and multidimensional arrays are useful for holding lists of lists and arrays of arrays. Jagged arrays are arrays of arrays, where each array has only as many elements as it needs. A nonjagged array is more like a grid or matrix, where every array needs to be the same size. Jagged arrays are much easier to work with (and use less memory), but nonjagged multidimensional arrays are sometimes useful for dealing with large grids of data.

Since a jagged array is an array of arrays, creating an item in a jagged array follows the same rules as creating an item in a regular array. If any of the arrays are single-element arrays, use the unary comma operator. For example, to create a jagged array with one nested array of one element:

PS > $oneByOneJagged = @(
 ,(,1)
)

PS > $oneByOneJagged[0][0]
1

For more information on lists and arrays in PowerShell, see “Arrays and Lists”.

See Also

“Arrays and Lists”