PowerShell: Combine Objects

By default, a PowerShell Custom Object cannot be added to another. This would be the error on each attempt:

PS C:\Windows\system32> $object1+$object2
Method invocation failed because [System.Management.Automation.PSObject] does not contain a method named 'op_Addition'.
At line:1 char:1
$object1+$object2
~~~~~ CategoryInfo : InvalidOperation: (op_Addition:String) [], RuntimeException
FullyQualifiedErrorId : MethodNotFound

--OR--
Method invocation failed because [Microsoft.PowerShell.Commands.MemberDefinition] does not contain a method named 'op_Addition'.
At line:5 char:13
$combinedMembers+=get-member -InputObject $object -Member … CategoryInfo : InvalidOperation: (op_Addition:String) [], RuntimeException
FullyQualifiedErrorId : MethodNotFound

Here’s a function to work around that problem:

function combineObjects($objects,$verbose=$false){
    $combinedMembers=@()
    foreach($object in $objects){
        if($object.gettype().BaseType.Name -eq 'Object'){
            $combinedMembers+=get-member -InputObject $object -MemberType NoteProperty
        }else{
            write-warning "This item is NOT an object:`r`n$object"
        }
    }    
    $newObject=New-Object -TypeName PSObject
    foreach($property in $combinedMembers){
        $propertyName=$property.Name
        $value=$property.Definition -replace '^.*='
        $propertyExists=$propertyName -in ($newobject|get-member).Name
        if(!$propertyExists){
            Add-Member -InputObject $newObject -MemberType NoteProperty -Name $propertyName -Value $value -Force
        }elseif($verbose){
            $previousValue=($newobject|get-member|?{$_.Name -eq $propertyName}).Definition -replace '^.*='
            write-warning "$propertyName value of previous value of $previousValue has NOT been replaced with $value"
        }
    }
    return $newObject
}

Leave a Reply

Your email address will not be published. Required fields are marked *