1

In PowerShell 4.0, Win 8.1, if I run this script:

$x = @(
    ("one","two","three"),
    ("four", "five", "six"),
    ("seven", "eight", "nine")
    )

write-host $x.Count
$x | % {write-host "$_"}

I get

3
one two three
four five six
seven eight nine

If I run the exact same script, but with the commas removed between each of the three sub-arrays:

$x = @(
    ("one","two","three")
    ("four", "five", "six")
    ("seven", "eight", "nine")
    )

write-host $x.Count
$x | % {write-host "$_"}

I get

9
one
two
three
four
five
six
seven
eight
nine

Interestingly, in the version with the commas removed, the newlines have to be there. If I remove them, the script won't run and gives "Unexpected token '(' in expression or statement" as the reason.

Why does this happen? My expectation is that it shouldn't run at all without the commas, regardless of the presence of newlines. This bit me when I added a new sub-array value to the bottom of a long array of similar values but forgot the comma, and the handling got all screwed up for the last value.

1 Answer 1

2

In the first example, you are defining a two dimensional array, and you get the expected behavior.

In the second example, what you are doing is defining a single dimensional array, basically the same as this:

$x = @("one","two","three","four","five","six","seven","eight","nine")

Except you are grouping it using parenthesis. That's why you need line break as well, because PowerShell is parsing what's inside the parenthesis as "one", like it does any command. And you can't have several commands on the same line without a line break (or a ';')

To verify, try this instead:

$x = @(("one","two","three");("four","five","six");("seven","eight","nine"))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! The "can't have several commands on the same line" was the intuition I was missing.

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.