problem with arrays

John Powers 1 Reputation point
2022-11-21T16:06:22.863+00:00

Hi. I am having trouble working with an array of arrays. Here is a simplified demonstrator of what I am trying to do and how it goes wrong. Say I have an array of arrays. I can create it quite easily with the command:

PS C:\work> $array = ((10,11,12),(20,21,22))

This creates what I expect - an array of 2 elements, each element being an array. I can confirm this with:

PS C:\work> $array.count; $array | foreach {[string]$_}
2
10 11 12
20 21 22

However if I try to add another element to this array, it splits that down into its atomic parts, such as:

PS C:\work> $array += (30,31,32)

  • and I do not get an array of 3 elements, but the 3rd broken up to make 5 elements, thus:

PS C:\work> $array.count; $array | foreach {[string]$_}
5
10 11 12
20 21 22
30
31
32

It has broken up the last array. I have tried other syntaxes
$array += ((30,31,32)) # (2 brackets, like the create)
$array += array # (force a variable type ARRAY)
but they all do the same thing. What am I misssing?

Many thanks for your help. John

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,364 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Rich Matheisen 44,776 Reputation points
    2022-11-21T16:32:57.587+00:00

    Ahhh, this needs the magic comma!

    $array = ((10,11,12),(20,21,22))  
    $array += ,(30,31,32)  
    $array.count; $array | foreach {[string]$_}  
    

    When you add an array, it's flattened. So "(30,31,32) is added one element of the array at a time. By placing the comma ahead of the array you're introducing an empty element and $null isn't passed through the implied pipeline (i.e., the flattening process). That leaves the array (the 2nd element of the array) to be added as an array because the comma is an array operator.