44

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
iTayb
  • 12,373
  • 24
  • 81
  • 135
  • NB: Where using an array of arrays it seems that the placement of the comma also matters. More info here: https://windowsserver.uservoice.com/forums/301869-powershell/suggestions/33859141-inconsistent-array-initialization-behaviour – JohnLBevan Apr 05 '18 at 10:53

1 Answers1

70

Adding a comma force to create an array:

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

Simple way:

$x = ,(1,2,3)
CB.
  • 58,865
  • 9
  • 159
  • 159
  • 4
    The magic comma strikes again! Why does powershell won't create array without comma? – jumbo Jun 21 '12 at 12:54
  • 10
    A good article on the magic : http://blogs.msdn.com/b/powershell/archive/2007/01/23/array-literals-in-powershell.aspx. The comma operator is the array construction operator in PowerShell – CB. Jun 21 '12 at 12:56
  • 7
    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. – David I. McIntosh Apr 14 '14 at 14:50
  • 3
    Microsoft broke the link in the comment above. The new location is https://blogs.msdn.microsoft.com/powershell/2007/01/23/array-literals-in-powershell/ – Tomalak May 10 '17 at 13:28
  • 4
    these types of 'conveniences' in a language are just asking for trouble. – orion elenzil Apr 20 '22 at 18:17