16

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
1

1 Answer 1

18

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:

https://devblogs.microsoft.com/powershell/array-literals-in-powershell/

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the link. This is quite odd syntax. I would interpret the example you give as defining $values[1,0] and $values[1,1].

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.