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: Windows Session Memory Usage Watcher

# windowsSessionWatcher.ps1 $serverNames=@( 'IRV-RDS01.domain1.net', 'LAX-RDS02.domain2.com ) $thresholdMemoryUsagePercent=30 $thresholdMemoryGb=20 $domainCreds=@( @{domain='domain1.ad';username='domain1\sysadmin';password=$env:pass1} @{domain='domain2.com';username='domain2\sysadmin';password=$env:pass2} ) # Email relay…

PowerShell: Scan a Subnet for Used and Unused IPs

A newer version of this script is available here. function scanForAvailableIPs{ param( $cidrBlock=$( $interfaceIndex=(Get-WmiObject -Class…

PowerShell: Monitor a Program Wizard for Its Task Completion

Once upon a time in the realm of SysAdmin endless green pastures, there were rampant…