Skip to content

Instantly share code, notes, and snippets.

@JohnLBevan
Last active March 15, 2023 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JohnLBevan/bdb145a5d31d49852954098a64b09d7b to your computer and use it in GitHub Desktop.
Save JohnLBevan/bdb145a5d31d49852954098a64b09d7b to your computer and use it in GitHub Desktop.
Gives you a way to compare 2 objects side by side to see what properties differ. The example shows how we could compare 2 user accounts from AD (arbitrarily picks the first 2 people called John from the directory for comparison)
function Compare-ArrayItems {
[CmdletBinding()]
Param (
[Parameter(Mandatory)]
[PSObject[]]$ReferenceArray
,
[Parameter(Mandatory)]
[PSObject[]]$DifferenceArray
)
# note: this treats the arrays as sets; i.e. doesn't care what position items are in within an array, or if the same item occurs multiple times
$union = ($ReferenceArray + $DifferenceArray) | Sort-Object -Unique
$union | ForEach-Object {
$inA = $_ -in ($ReferenceArray)
$inB = (!$inA) -or ($_ -in ($DifferenceArray))
([PSCustomObject]@{
Item = $_
Compare = $(if ($inA -and $inB){0}else{if($inA){1}else{-1}})
Reference = $inA
Difference = $inB
})
}
}
# get some example users
$a,$b,$ignoretail = Get-AdUser -filter "givenname -eq 'John'" -Properties MemberOf
# get their memberof info in a more readable format
$aGroups = $a.memberof | %{$_ -replace '^CN=(.*?),OU=.*','$1'}
$bGroups = $b.memberof | %{$_ -replace '^CN=(.*?),OU=.*','$1'}
# compare
Compare-ArrayItems $aGroups $bGroups |
Where-Object {$_.Compare -ne 0} |
Format-Table -AutoSize
function Compare-ObjectProperties {
[CmdletBinding()]
Param (
[Parameter(Mandatory)]
[PSObject]$ReferenceObject
,
[Parameter(Mandatory)]
[PSObject]$DifferenceObject
)
$props = (@($ReferenceObject | Get-Member -MemberType Properties | Select-Object -ExpandProperty Name) + @($DifferenceObject | Get-Member -MemberType Properties | Select-Object -ExpandProperty Name)) | Sort-Object -Unique
$props | %{
([PSCustomObject]@{
Property = $_
Compare = $(if ($ReferenceObject."$_" -eq $DifferenceObject."$_") {0} else {try{@(-1,1)[$ReferenceObject."$_" -lt $DifferenceObject."$_"]}catch{'?'}})
Reference = $ReferenceObject."$_"
Difference = $DifferenceObject."$_"
})
}
}
$a,$b,$ignoretail = Get-AdUser -filter "givenname -eq 'John'" -Properties *
$colFormats = @(
@{L='Property'; E={$_.Property}; W= 30},
@{L='='; E={$_.Compare}; W= 1},
@{L='Reference'; E={$_.Reference}; W=100},
@{L='Difference'; E={$_.Difference}; W=100}
)
Compare-ObjectProperties -ReferenceObject $a -DifferenceObject $b |
Where-Object{$_.Compare -ne 0} |
Format-Table $colFormats
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment