|
| 1 | +<# |
| 2 | +.SYNOPSIS |
| 3 | +Create a new PSObject by recursively combining the properties of PSObjects. |
| 4 | +
|
| 5 | +.INPUTS |
| 6 | +System.Management.Automation.PSObject to combine. |
| 7 | +
|
| 8 | +.OUTPUTS |
| 9 | +System.Management.Automation.PSObject combining the inputs. |
| 10 | +
|
| 11 | +.FUNCTIONALITY |
| 12 | +PowerShell |
| 13 | +
|
| 14 | +.LINK |
| 15 | +Get-Member |
| 16 | +
|
| 17 | +.LINK |
| 18 | +Add-Member |
| 19 | +
|
| 20 | +.EXAMPLE |
| 21 | +Merge-PSObject ([pscustomobject]@{a=1;b=2}) ([pscustomobject]@{b=0;c=3}) |
| 22 | +
|
| 23 | +a b c |
| 24 | +- - - |
| 25 | +1 2 3 |
| 26 | +
|
| 27 | +.EXAMPLE |
| 28 | +Merge-PSObject ([pscustomobject]@{a=1;b=2}) ([pscustomobject]@{b=0;c=3}) -Force |
| 29 | +
|
| 30 | +a b c |
| 31 | +- - - |
| 32 | +1 0 3 |
| 33 | +
|
| 34 | +.EXAMPLE |
| 35 | +'{"a":1,"b":{"u":3},"c":{"v":5}}','{"a":{"w":8},"b":2,"c":{"x":6}}' |ConvertFrom-Json |Merge-PSObject -Accumulate -Force |select -Last 1 |ConvertTo-Json |
| 36 | +
|
| 37 | +{ |
| 38 | + "a": { |
| 39 | + "w": 8 |
| 40 | + }, |
| 41 | + "b": 2, |
| 42 | + "c": { |
| 43 | + "v": 5, |
| 44 | + "x": 6 |
| 45 | + } |
| 46 | +} |
| 47 | +#> |
| 48 | + |
| 49 | +[CmdletBinding()][OutputType([PSObject])] Param( |
| 50 | +# Initial PSObject to combine. |
| 51 | +[Parameter(Position=0)][PSObject] $ReferenceObject = [pscustomobject]@{}, |
| 52 | +<# |
| 53 | +PSObjects to combine. PSObject descendant properties are recursively merged. |
| 54 | +Primitive values are overwritten by any matching ones in the new PSObject. |
| 55 | +#> |
| 56 | +[Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$true)][PSObject] $InputObject, |
| 57 | +# Continue merging each pipeline object's properties into the same accumulator object. |
| 58 | +[switch] $Accumulate, |
| 59 | +# Overwrite existing properties. |
| 60 | +[switch] $Force |
| 61 | +) |
| 62 | +Begin {if($Accumulate) {$value = $ReferenceObject.PSObject.Copy()}} |
| 63 | +Process |
| 64 | +{ |
| 65 | + if(!$Accumulate) {$value = $ReferenceObject.PSObject.Copy()} |
| 66 | + foreach($p in $InputObject |Get-Member -Type Properties) |
| 67 | + { |
| 68 | + $name,$type = $p.Name,$p.MemberType |
| 69 | + $newvalue = $InputObject.$name |
| 70 | + if(!($value |Get-Member $name -Type $type)) |
| 71 | + { |
| 72 | + $value |Add-Member $name -Type $type -Value $newvalue |
| 73 | + } |
| 74 | + elseif($Force) |
| 75 | + { |
| 76 | + $currentvalue = $value.$name |
| 77 | + $value.$name = |
| 78 | + if($currentvalue -isnot [PSObject] -or $newvalue -isnot [PSObject]) {$newvalue} |
| 79 | + else {Merge-PSObject $currentvalue $newvalue} |
| 80 | + } |
| 81 | + elseif($value.$name -is [PSObject] -and $newvalue -is [PSObject]) |
| 82 | + { |
| 83 | + $value.$name = Merge-PSObject $value.$name $newvalue |
| 84 | + } |
| 85 | + } |
| 86 | + return $value |
| 87 | +} |
0 commit comments