Combining Objects

by Dec 7, 2012

Sometimes it becomes necessary to consolidate two or more objects into one. So, how would you combine object properties into one object?

In a previous tip we illustrated how you can convert an object into a hash table. In PowerShell 3.0, Add-Member is now able to take a hash table and add its contents as note properties to another object.

Here is sample code. It gets BIOS information and operating system information from the WMI. These are two separate objects. Now, the BIOS object is converted into a hash table and then added to the other object.

$os now contains the properties of both objects (conflicting properties are removed which is why errors are suppressed):

$bios = Get-WmiObject -Class Win32_BIOS
$os = Get-WmiObject -Class Win32_OperatingSystem
$hashtable = $bios | 
  Get-Member -MemberType *Property | 
  Select-Object -ExpandProperty Name | 
  Sort-Object | 
  ForEach-Object { $rv=@{} } { Write-Warning $_$rv.$_ = $bios.$_ } {$rv}

$os | Add-Member ($hashtable) -ErrorAction SilentlyContinue

When you output $os, at first sight it did not seem to change because PowerShell continues to display the default properties. However, the BIOS information is now added to it:

PS> $os | Select-Object *BIOS*

BiosCharacteristics : {7, 11, 12, 15...}
BIOSVersion         : {APPLE  - 60}

Twitter This Tip! ReTweet this Tip!