Created
November 24, 2021 17:03
-
-
Save petervandivier/eca349d452f675a71ac464a05f34052b to your computer and use it in GitHub Desktop.
Merge-ObjectArray.ps1
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 Merge-ObjectArray { | |
<# | |
.DESCRIPTION | |
Converts an array of objects into a single object with all constituent | |
properties of each input. If a synonymous property is detected between | |
inputs, the value is overwritten and a warning is raised but the merge | |
continues. | |
.EXAMPLE | |
$foo = @{foo=1} | |
$bar = [PSCustomObject]@{bar=1} | |
$baz = [PSCustomObject]@{bar=2;baz=1} | |
# | |
($foo,$bar,$baz) | Merge-ObjectArray | |
#> | |
[CmdletBinding()] | |
param ( | |
[Parameter(ValueFromPipeline)] | |
[Object[]] | |
$ObjectArray | |
) | |
begin{ | |
$ReturnObject = [Object]::new() | |
} | |
process { | |
foreach($obj in $ObjectArray[0..($ObjectArray.Length)]){ | |
# [Ordered] inputs here are flattened into [PSCustomObject] explicitly | |
foreach ($Property in ([PSCustomObject]$obj).PSObject.Properties) { | |
if($ReturnObject.($Property.Name)){ | |
Write-Warning "Property '$($Property.Name)' already declared - current value of '$($ReturnObject.($Property.Name))' will be overwritten to '$($Property.Value)'" | |
$ReturnObject.($Property.Name) = $Property.Value | |
} | |
else { | |
$ReturnObject | Add-Member -MemberType NoteProperty -Name $Property.Name -Value $Property.Value | |
} | |
} | |
} | |
} | |
end { | |
return [pscustomobject] $ReturnObject | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment