PowerShell, Pulling out multiple arrays from an variable to make a single variable

Solution 1:

What you're trying to do is usually known as "merge arrays" or "join arrays". There are many ways to approach this, for example, with a for loop.

To answer your first question, $metrics is an object, and as any object it can have properties and methods. In this case, your object has 3 properties which are arrays. To give some perspective on how you can approach this in the future, it's key to know about the .GetType() method and Get-Member.

This is a recreation of your object using [PSCustomObject]:

$metrics = [pscustomobject]@{
    Id         = 'cpuUtil01'
    Label      = 'CPUUtilization'
    Messages   = @()
    StatusCode = 'Complete'
    Timestamps = '11/27/2021 7:00:00 PM','11/27/2021 7:05:00 PM','11/27/2021 7:10:00 PM'
    Values     = '51.22','31.3833333333333','31.4116666666667','31.5283333333333'
}

Now we can put it into practice:

PS /> $metrics.GeTtype()

IsPublic IsSerial Name             BaseType
-------- -------- ----             --------
True     False    PSCustomObject   System.Object

PS /> $metrics.Values.GetType()

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

PS /> $metrics | Get-Member

   TypeName: System.Management.Automation.PSCustomObject

Name        MemberType   Definition
----        ----------   ----------
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()
GetType     Method       type GetType()
ToString    Method       string ToString()
Id          NoteProperty string Id=cpuUtil01
Label       NoteProperty string Label=CPUUtilization
Messages    NoteProperty Object[] Messages=System.Object[]
StatusCode  NoteProperty string StatusCode=Complete
Timestamps  NoteProperty Object[] Timestamps=System.Object[]
Values      NoteProperty Object[] Values=System.Object[]

Now to answer the main question, how to merge both arrays?:

  • First we need to know if both have the same length, else we would be losing information:
$maxCount = [math]::Max($metrics.TimeStamps.Count, $metrics.Values.Count)

Then just loop over each element of each array using a for loop creating a new object out of their values:

$result = for($i = 0; $i -lt $maxCount; $i++)
{
    [pscustomobject]@{
        TimeStamps = $metrics.TimeStamps[$i]
        Values = $metrics.Values[$i]
    }
}
PS /> $result

TimeStamps            Values
----------            ------
11/27/2021 7:00:00 PM 51.22
11/27/2021 7:05:00 PM 31.3833333333333
11/27/2021 7:10:00 PM 31.4116666666667
11/27/2021 7:15:00 PM 31.5283333333333