iTayb
iTayb

Reputation: 12743

How do I create array of arrays in PowerShell?

I want to create an array of arrays in PowerShell.

$x = @(
    @(1,2,3),
    @(4,5,6)
)

It works fine. However, sometimes I have only one array in the array list. In that situation, PowerShell ignores one of the lists:

$x = @(
    @(1,2,3)
)

$x[0][0] # Should return 1
Unable to index into an object of type System.Int32.
At line:1 char:7
+ $a[0][ <<<< 0]
    + CategoryInfo          : InvalidOperation: (0:Int32) [], RuntimeException
    + FullyQualifiedErrorId : CannotIndex

How do I create an array of arrays, guaranteed it remains as a two-dimensional array even if the array has only one array item in it?

Upvotes: 48

Views: 54627

Answers (1)

CB.
CB.

Reputation: 60918

Adding a comma force to create an array:

$x = @(
    ,@(1,2,3)
)

Simple way:

$x = ,(1,2,3)

Upvotes: 75

Related Questions