Powershell: Adding an Array as a member of another array

Viewed 119

In Powershell I have 3 arrays similar to the below:

Array1:

Date          Value
----          -----
26/06/2021    5
25/05/2021    10
24/06/2021    4


Array2:

Value
-----
9
8
4

Array3:

Value
-----
11
15
20

I want to be able to add the values from Array2 and Array3 as members of Array1 so it finishes up like the below:

Array1:

    Date          Value    Value2    Value3
    ----          -----    ------    ------
    26/06/2021    5        9         11
    25/05/2021    10       8         15
    24/06/2021    4        4         20

For the life of me i can't find out how to do this - all I have managed to do is add the values from Array2 and 3 to the bottom of Array1 but that is not what I'm after.

Is anyone able to help?

1 Answers

It's not so much that you'll want to add them to the first array - instead, you'll want to create a new array consisting of new objects that have the property values from all three source arrays.

We can create new objects by casting a hashtable literal to [pscustomobject], so all we need to do is align the items in the arrays.

A simple for loop will do:

for($i = 0; $i -lt $array1.Length; $i++){
  [pscustomobject]@{
    Date   = $array1[$i].Date
    Value  = $array1[$i].Value
    Value2 = $array2[$i].Value
    Value3 = $array3[$i].Value
  }
}
Related