Please feel free to provide feedback or file bugs here.

Inconsistent Array Initialization Behaviour

Creating an array of arrays as below works well:

$myArray = @(
@(1,2,3),
@(4,5,6)
)
$myArray[0] #outputs 1, 2, 3
$myArray[1] #outputs 4, 5, 6

$myBuggyArray = @(
@(1,2,3)
,@(4,5,6)
)
$myBuggyArray[0] #outputs 1
$myBuggyArray[3] #outputs 4, 5, 6

I wouldn't expect the order of line break & comma to impact the behaviour of the command / can't find any documentation stating that it should.

PSVersion: 5.1.14409.1012

5 votes
Sign in
Check!
(thinking…)
Reset
or sign in with
  • facebook
  • google
    Password icon
    Signed in as (Sign out)

    We’ll send you updates on this idea

    John Bevan shared this idea  ·   ·  Flag idea as inappropriate…  ·  Admin →

    3 comments

    Sign in
    Check!
    (thinking…)
    Reset
    or sign in with
    • facebook
    • google
      Password icon
      Signed in as (Sign out)
      Submitting...
      • Chris commented  ·   ·  Flag as inappropriate

        Not a bug, but granted unexpected. Review: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operators?view=powershell-6

        @( ) Array subexpression operator
        Returns the result of one or more statements as an array. If there is only one item, the array has only one member.

        @(
        @(1,2,3)
        @(4,5,6)
        )[0] # Out 1
        This is not a nested array because the inner subexpressions are evaluated and the resulting elements gathered into the outer array.

        , Comma operator
        As a binary operator, the comma creates an array. As a unary operator, the comma creates an array with one member. Place the comma before the member.

        @(1,2,3),
        @(4,5,6)
        Here the comma is a binary operator which results in the second line being treated as a continuation of the first line and creating the expected nested array.

        @(1,2,3)
        ,@(4,5,6)
        Here we have two individual statements. The first evaluates to three elements. In the second he comma is a unary operator which creates a single member array (with a nested array in it).

      • Anonymous commented  ·   ·  Flag as inappropriate

        To my untrained eyes, it looks like a tokenization/parsing error... and a maddening one at that.

      • lee_dailey commented  ·   ·  Flag as inappropriate

        howdy John Bevan,

        a leading comma does something special with arrays. i don't know what it should do in your sample code, but it otta force an array to be added as an array, not as more elements in the 1st array.

        running our code sample, i get 1,4,5,6 for the [3] item in the array.

        it certainly aint what i expected. [*sigh ...*]

        take care,
        lee

      Feedback and Knowledge Base