Skip to content

Instantly share code, notes, and snippets.

@petervandivier
Created November 24, 2021 17:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petervandivier/eca349d452f675a71ac464a05f34052b to your computer and use it in GitHub Desktop.
Save petervandivier/eca349d452f675a71ac464a05f34052b to your computer and use it in GitHub Desktop.
Merge-ObjectArray.ps1
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