PowerShell cmdlet to get attributes not matching between two objects

This is a very quick cmdlet for getting attributes that does not match between two objects

<#
.Synopsis
   Returns a list of all attributes that does not match between two objects
#>
function Get-MismatchedAttributes
{
    [CmdletBinding()]
    [OutputType([boolean])]
    Param
    (
        [Parameter(Mandatory=$true,
                    ValueFromPipelineByPropertyName=$false,
                    Position=0)]
        $ReferenceObject,
              
        [Parameter(Mandatory=$true,
                    ValueFromPipelineByPropertyName=$false,
                    Position=1)]
        $DifferenceObject,

        [Parameter(Mandatory=$false,
                    ValueFromPipelineByPropertyName=$false,
                    Position=2)]
        [String[]] $Attributes = $null
    )

    if($Attributes -eq $null) {
        $Attributes = @(
            $ReferenceObject | gm -MemberType NoteProperty | select -exp Name
            $DifferenceObject | gm -MemberType NoteProperty | select -exp Name
        ) | Sort -Unique
    }
    
    $Attributes | Where {$ReferenceObject.$($_) -ne $DifferenceObject.$($_)}
}



$obj1 = [PSCustomObject] @{
    Attr1 = "abc"
    Attr2 = "def"
    Attr3 = "klm"
}

$obj2 = [PSCustomObject] @{
    Attr1 = "abc"
    Attr2 = "okj"
}

Write-Host "Attributes that does not match, limited to Attr1 and Attr2" -ForegroundColor Red
Get-MismatchedAttributes $obj1 $obj2 -Attributes "Attr1","Attr2"

Write-Host "All attributes that does not match" -ForegroundColor Red
Get-MismatchedAttributes $obj1 $obj2

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s