function Merge-Property {
<#
.Synopsis
Merges
properties / keys of the Secondary object / hashtable to the Primary object /
hashtable.
.DESCRIPTION
This function
takes all properties or keys of the Secondary object / hashtable into the
Primary object or hashtable. By default only those properties / keys are merge
that doesn't exist in the Primary object / hashtable.
If the -Force
switch is used then the properties / keys of the Secondary object / hashtable
always merged to the Primary.
.EXAMPLE
$p = @{one =
1; three = 3}; $s = [pscustomobject]@{two = 2; three = 33; four = 4};
Merge-Property -Primary $p -Secondary $s -PassThru
Merges $s
into $p. The updated hashtable will have its key 'three' remained to be 3.
.EXAMPLE
$p = @{one =
1; three = 3}; $s = [pscustomobject]@{two = 2; three = 33; four = 4};
Merge-Property -Primary $p -Secondary $s -PassThru -Force
Merges $s
into $p. The updated hashtable will have its key 'three' updated to be 33.
.INPUTS
hashtables or
psobjects
.OUTPUTS
None or the
updated object of the Primary object if the -PassThru switch is used.
#>
[cmdletbinding()]
param(
# Primary object or
hashtable to merge the properties of Secondary into.
[Parameter(Mandatory
=
$true)][PSobject]
$Primary,
# Secondary object
or hashtable whose properties or keys to be merged into Primary.
[Parameter(Mandatory
=
$true)][PSobject]
$Secondary,
# If used then the
updated primary objects is returned.
[switch]
$PassThru,
# By default
conflicting properties / keys are skipped. In case the -Force switch is used
then conflicting properties / keys of Primary will be overwritten by properties
/ keys of Secondary.
[switch]
$Force
)
if($Primary
-is
[hashtable]){
if($Secondary
-is
[hashtable]){
foreach($key
in
$Secondary.keys){
if($Force
-or
!$Primary.containskey($key)){
$Primary.$key =
$Secondary.$key
}
}
}
else{
foreach($prop
in
$Secondary.psobject.properties.name){
if($Force
-or
!$Primary.containskey($prop)){
$Primary.$prop =
$Secondary.$prop
}
}
}
}
else{
if($Secondary
-is
[hashtable]){
foreach($key
in
$Secondary.keys){
if($Force
-or
$Primary.psobject.properties.name
-notcontains
$key){
Add-Member -InputObject
$Primary
-MemberType
NoteProperty -Name
$key
-Value
$Secondary.$key
-Force
}
}
}
else{
foreach($prop
in
$Secondary.psobject.properties.name){
if($Force
-or
$Primary.psobject.properties.name
-notcontains
$prop){
Add-Member -InputObject
$Primary
-MemberType
NoteProperty -Name
$prop
-Value
$Secondary.$prop
-Force
}
}
}
}
if($PassThru){
$Primary
}
}
PS C:\> $p = @{one = 1; three = 3}; $s = [pscustomobject]@{two = 2; three = 33; four = 4}
PS C:\> Merge-Property -Primary $p -Secondary $s -PassThru
Name Value
---- -----
four 4
one 1
three 3
two 2
PS C:\> $p = @{one = 1; three = 3}; $s = [pscustomobject]@{two = 2; three = 33; four = 4}
PS C:\> Merge-Property -Primary $p -Secondary $s -PassThru -Force
Name Value
---- -----
four 4
one 1
three 33
two 2