Search code examples
powershellpowershell-2.0powershell-3.0psobjectpscustomobject

Append 2 pscustomobjects into 1


enter image description here

I am new to powershell. I have 2 pscustomobjects in powershell script. I want to bring them together as one and output into csv.

The problem is there is no key column to match in both, just want to append them together. I was able to use the following code but it does not show the data correctly. Any Suggestions? (sample attached)

$result=[pscustomobject]($a+$b)

Solution

  • It seems what you're looking to do is merge the properties from both objects into one.

    You can access the properties and property values of an object via the intrinsic member PSObject, in this case you would need to enumerate all properties from both objects ($a and $b) and put them together into an ordered dictionary and lastly cast [pscustomobject] to it to get a new merged object as a result. This function can simplify that process for you.

    function Merge-PSCustomObject {
        param(
            [Parameter(Mandatory)]
            [Object] $LeftObject,
    
            [Parameter(Mandatory)]
            [Object] $RigthObject
        )
    
        end {
            $result = [ordered]@{}
            foreach($property in @($LeftObject.PSObject.Properties; $RigthObject.PSObject.Properties)) {
                $result[$property.Name] = $property.Value
            }
            [pscustomobject] $result
        }
    }
    
    $a = [pscustomobject]@{ foo = 'hello' }
    $b = [pscustomobject]@{ bar = 'world'; baz = 123 }
    
    Merge-PSCustomObject -LeftObject $a -RigthObject $b
    

    If you have an array of objects in both sides, assuming both arrays have the same count of objects, you can use a for loop to merge each object in both arrays, for example:

    $a = [pscustomobject]@{ foo = 'hello' }
    $b = [pscustomobject]@{ bar = 'world'; baz = 123 }
    
    $arr1 = 0..3 | ForEach-Object { $a }
    $arr2 = 0..3 | ForEach-Object { $b }
    
    $result = for($i = 0; $i -lt $arr1.Count; $i++) {
        Merge-PSCustomObject $arr1[$i] $arr2[$i]
    }