50

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?

1

1 Answer 1

77

Adding a comma force to create an array:

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

Simple way:

$x = ,(1,2,3)
Sign up to request clarification or add additional context in comments.

5 Comments

The magic comma strikes again! Why does powershell won't create array without comma?
A good article on the magic : blogs.msdn.com/b/powershell/archive/2007/01/23/…. The comma operator is the array construction operator in PowerShell
Of course, then for consistency of syntax, you would hope that this @( ,@(1,2,3) ,@(4,5,6) ) would work... but it doesn't give you what you expect. Sigh.
Microsoft broke the link in the comment above. The new location is blogs.msdn.microsoft.com/powershell/2007/01/23/…
these types of 'conveniences' in a language are just asking for trouble.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.