2

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?

2

1 Answer 1

4

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
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

+1 on the concise iteration. Something maybe helpful (or not) to add would be that if you wish to refer to say $Array1.Value2 or $Array1.Value3 etc.. then you could set the above into $Array1: $Array1 = for($i =0 ..... etc...

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.