Skip to content

Instantly share code, notes, and snippets.

@KirkMunro
Created June 6, 2017 15:42
Show Gist options
  • Save KirkMunro/8af982d54fa096cb60309dca9ccdd847 to your computer and use it in GitHub Desktop.
Save KirkMunro/8af982d54fa096cb60309dca9ccdd847 to your computer and use it in GitHub Desktop.
A function that facilitates comparison of serialized objects with their deserialized or selected equivalent
function Compare-ObjectEquivalence {
[CmdletBinding(DefaultParameterSetName='Deserialized')]
param(
[Parameter(Position=0, Mandatory=$true)]
[ValidateNotNull()]
[System.Object]
$OriginalObject,
[Parameter(Position=1, Mandatory=$true, ParameterSetName='Deserialized')]
[ValidateNotNull()]
[System.Object]
$DeserializedObject,
[Parameter(Position=1, Mandatory=$true, ParameterSetName='Selected')]
[ValidateNotNull()]
[System.Object]
$SelectedObject,
[Parameter(Position=2)]
[ValidateNotNullOrEmpty()]
[System.String[]]
$Property
)
try {
$comparisonParameterName = "$($PSCmdlet.ParameterSetName)Object"
$comparisonObject = $PSCmdlet.MyInvocation.BoundParameters[$comparisonParameterName]
$originalObjectType = $OriginalObject.GetType()
$equivalent = $originalObjectType -eq $comparisonObject.GetType() -or
$comparisonObject.PSTypeNames -match "$($PSCmdlet.ParameterSetName).$($originalObjectType.FullName)"
if ($equivalent) {
if (-not $PSCmdlet.MyInvocation.BoundParameters.ContainsKey('Property')) {
$Property = @($comparisonObject.PSObject.Properties | Select-Object -ExpandProperty Name)
}
foreach ($entry in $PSCmdlet.MyInvocation.BoundParameters['Property']) {
if ($originalObject.$entry.GetType().IsValueType -or $originalObject.$entry -is [string]) {
if ($originalObject.$entry -ne $comparisonObject.$entry) {
$equivalent = $false
break
}
} else {
$recurseParameters = @{
OriginalObject = $originalObject.$entry
"$comparisonParameterName" = $comparisonObject.$entry
}
Compare-ObjectEquivalence @recurseParameters
}
}
}
$equivalent
} catch {
$PSCmdlet.ThrowTerminatingError($_)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment