It seems what you're looking to do is merge the properties from both objects into one.
You can access the properties and property values of an object via the intrinsic member PSObject
, in this case you would need to enumerate all properties from both objects ($a
and $b
) and put them together into an ordered dictionary and lastly cast [pscustomobject]
to it to get a new merged object as a result. This function can simplify that process for you.
function Merge-PSCustomObject {
param(
[Parameter(Mandatory)]
[Object] $LeftObject,
[Parameter(Mandatory)]
[Object] $RigthObject
)
end {
$result = [ordered]@{}
foreach($property in @($LeftObject.PSObject.Properties; $RigthObject.PSObject.Properties)) {
$result[$property.Name] = $property.Value
}
[pscustomobject] $result
}
}
$a = [pscustomobject]@{ foo = 'hello' }
$b = [pscustomobject]@{ bar = 'world'; baz = 123 }
Merge-PSCustomObject -LeftObject $a -RigthObject $b
If you have an array of objects in both sides, assuming both arrays have the same count of objects, you can use a for
loop to merge each object in both arrays, for example:
$a = [pscustomobject]@{ foo = 'hello' }
$b = [pscustomobject]@{ bar = 'world'; baz = 123 }
$arr1 = 0..3 | ForEach-Object { $a }
$arr2 = 0..3 | ForEach-Object { $b }
$result = for($i = 0; $i -lt $arr1.Count; $i++) {
Merge-PSCustomObject $arr1[$i] $arr2[$i]
}