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: HashMap Enumeration Example – Set Active-X on Internet Explorer

function allowActiveX($zone='Trusted'){ #Source: https://learn.microsoft.com/en-us/previous-versions/troubleshoot/browsers/security-privacy/ie-security-zones-registry-entries #Reference table: #Value Setting #------------------------------ #0 My Computer #1 Local Intranet…

Manually Create a SSL Certificate with LetsEncrypt

Step 1: Install certbot-auto mkdir /etc/letsencryptcd /etc/letsencrypt/wget chmod a+x certbot-auto Step 2: Create the Cert…

PowerShell: Quick Script to Get Storage Utilization

$volumes = (gwmi -Class win32_volume -Filter "DriveType!=5" -ea stop| ?{$_.DriveLetter -ne $isnull}|` Select-object @{Name="Letter";Expression={$_.DriveLetter}},` @{Name="Label";Expression={$_.Label}},`…