Last active
April 28, 2021 12:53
-
-
Save julian-wendt/01a35c153e118a59546af333d60eaa41 to your computer and use it in GitHub Desktop.
Join-Object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Join-Object { | |
<# | |
.SYNOPSIS | |
Join properties of two objects into one. | |
.DESCRIPTION | |
Compare properties from two objects and join them into one. | |
If properties exist in both objects and their values are not equal, reference values will be replaced. | |
Properties which only exist in the difference object will be added to the reference object. | |
Important: Objects must have the same type. Arrays and hashtables cannot be joined. | |
.PARAMETER ReferenceObject | |
Object to update. | |
.PARAMETER DifferenceObject | |
Object containing new properties and values to add. | |
.EXAMPLE | |
Join-Object -ReferenceObject $Object1 -DifferenceObject $Object2 | |
#> | |
param( | |
[Parameter(Mandatory = $true)] | |
[system.object]$ReferenceObject, | |
[Parameter(Mandatory = $true)] | |
[system.object]$DifferenceObject | |
) | |
$ReferenceKeys = ($ReferenceObject | Get-Member -MemberType NoteProperty).Name | |
$DifferenceKeys = ($DifferenceObject | Get-Member -MemberType NoteProperty).Name | |
# Working with hashtables? | |
$HashTable = [bool]('Hashtable' -in ($ReferenceObject.GetType().Name, $DifferenceObject.GetType().Name)) | |
# Gather differently for hashes | |
if ($HashTable) { | |
$ReferenceKeys = $ReferenceObject.Keys | |
$DifferenceKeys = $DifferenceObject.Keys | |
} | |
foreach ($Property in $DifferenceKeys) { | |
# Add missing property to reference object | |
if ($Property -notin $ReferenceKeys -and $Hashtable.IsPresent -eq $true) { | |
$ReferenceObject.Add($Property, 'null') | |
} | |
elseif ($Property -notin $ReferenceKeys -and $Hashtable.IsPresent -eq $false) { | |
$ReferenceObject | Add-Member -MemberType NoteProperty -Name $Property -Value $null | |
} | |
# Set new value | |
if ($DifferenceObject.$Property -ne $ReferenceObject.$Property) { | |
$ReferenceObject.$Property = $DifferenceObject.$Property | |
} | |
} | |
return $ReferenceObject | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment