Skip to content

Instantly share code, notes, and snippets.

@julian-wendt
Last active April 28, 2021 12:53
Show Gist options
  • Save julian-wendt/01a35c153e118a59546af333d60eaa41 to your computer and use it in GitHub Desktop.
Save julian-wendt/01a35c153e118a59546af333d60eaa41 to your computer and use it in GitHub Desktop.
Join-Object
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