3

I noticed a difference between those two declarations where only the position of the comma changes:

$a = @( @('a','b'),
        @('c','d'))

$b = @( @('a','b')
      , @('c','d'))

In this case, $a.length evaluates to 2 and $b.length evaluates to 3. The first sub-array of $b has been flattened.

Is this a feature and where can I find its documentation?

By the way, $PSVersionTable:

Name                           Value
----                           -----
PSVersion                      4.0
WSManStackVersion              3.0
SerializationVersion           1.1.0.1
CLRVersion                     4.0.30319.42000
BuildVersion                   6.3.9600.16406
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion      2.2

1 Answer 1

2
 , 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.

Source.

Its because @('a','b') will push two strings a and b into the array $b whereas you force @('c','d')to get pushed into $b as an array using a comma.

Example:

$b = @( @('a','b')
      , @('c','d'))

$b | foreach { Write-Host "Item: $_"}

Output:

Item: a
Item: b
Item: c d

And if you look at the types:

$b | foreach { $_.GetType()}

You get:

IsPublic IsSerial Name     BaseType     
-------- -------- ----     --------     
True     True     String   System.Object
True     True     String   System.Object
True     True     Object[] System.Array 

To force $b to contain two arrays, use the comma binary operator:

$b = @(@('a','b'),@('c','d'))
Sign up to request clarification or add additional context in comments.

4 Comments

I am sorry, I don't understand your answer. $b = @(@('a','b'),@('c','d')) contains two arrays without comma. What is the difference when I insert newline BEFORE the comma and AFTER the comma?
You are right. Its because in this case the comma is used as a binary operator, see my edit.
Does that mean binary operators cannot follow newline?
Yes it does. You can validate that if you adding a backtick ` to the end of the first line, then the comma is treated as a binary operator

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.