Posted On October 1, 2020

PowerShell: Combine Objects

kimconnect 0 comments
blog.KimConnect.com >> Codes >> 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 *

Related Post

PowerShell: Methods to Download Files

# Change these values to reflect your desired downloads$fileURL = "https://download.microsoft.com/download/0/d/9/0d9d81cf-4ef2-4aa5-8cea-95a935ee09c9/PortQryV2.exe"$output = "C:\WINDOWS\System32\SysInternals\portqry.exe"1. Start-BitsTransfer (my…

PowerShell: Legacy Methods to Save Credentials

PowerShell version 7 or later may already have facilities to store and retrieve credentials without…

PowerShell: Install App Using MSI on Remote Computers Via WinRM

# installMSiRemoteComputers.ps1 # version 0.0.1 $computernames='REMOTEPC001','REMOTEPC002' $thisMsiFile='C:\Temp\something.msi' $appName='testapp' $desiredVersion='1.0' $maxWaitSeconds=120 function installMsiOnRemoteComputers($computernames,$msiFile,$appName,$desiredVersion,$maxWaitSeconds){ function installMsiOnRemoteComputer{ param(…