Powershell: Two dimension arrays

Michael Frederick picture Michael Frederick · Aug 16, 2013 · Viewed 83.5k times · Source

The following works as expected:

$values = @( ("a", "b"), ("c", "d") )
foreach($value in $values)
{
  write-host "Value 0 =" $value[0]
  write-host "Value 1 =" $value[1]
}

which results(1) in:

Value 0 = a
Value 1 = b
Value 0 = c
Value 1 = d

But if I change the $values variable to:

$values = @( ("a", "b") )

the result(2) is:

Value 0 = a
Value 1 =
Value 0 = b
Value 1 =

whereas I would have expected the result(3) to be:

Value 0 = a
Value 1 = b

Changing the $value to:

$values = @( ("a"), ("b") )

gives the same result as result(2) above. These are very different data representations.

The script that I am writing needs to be able to handle two-dimensional arrays where the first dimension has length from 0 thru N. I would like to be able to write the script so that if a first-level element needs to be added (or removed) that I don't have to change the logic of the script; I'd like to be able to just edit the "data".

So my question is: How do I notate a two-dimensional array so the shown foreach loop will work correctly when the first dimension of the array has a length of 1?

get-host responds with:

Name             : ConsoleHost
Version          : 2.0
InstanceId       : 2338657f-e474-40d8-9b95-7e2b5f6a8acf
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : en-US
CurrentUICulture : en-US
PrivateData      : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
IsRunspacePushed : False
Runspace         : System.Management.Automation.Runspaces.LocalRunspace

Answer

Andy Arismendi picture Andy Arismendi · Aug 16, 2013

This is another case where PowerShell's array handling behavior may cause unexpected results.

I think you'll need to use the comma trick (the array operator) to get the desired result:

$values = @( ,("a", "b") )
foreach($value in $values)
{
  write-host "Value 0 =" $value[0]
  write-host "Value 1 =" $value[1]
}

Result:

Value 0 = a
Value 1 = b

Actually all you need is this:

$values = ,("a", "b")

This article explains more about PowerShell's handling of arrays:

http://blogs.msdn.com/b/powershell/archive/2007/01/23/array-literals-in-powershell.aspx