Question:
I am trying to combine multiple object properties into one object.
When I have the following code the objects properties are combined.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$computer = gwmi win32_computersystem | select numberOfProcessors, NumberOfLogicalProcessors, HypervisorPresent $osInfo = gwmi win32_operatingsystem | select version, caption, serialnumber, osarchitecture Foreach($p in Get-Member -InputObject $osInfo -MemberType NoteProperty) { Add-Member -InputObject $computer -MemberType NoteProperty -Name $p.Name -Value $osInfo.$($p.Name) -Force } $computer |
However, if I replace the above computer and osInfo variables with
1 2 3 |
$computer = Get-Process | Select processname, path $osInfo = Get-Service | Select name, status |
then the $computer
variables does not have the properties of the $osInfo
variable after the for loop is executed. ie: the second object is not combined with the first object.
Answer:
The original code deals with cmdlets that returns two single objects relating to the same source.
You’re trying to use it with cmdlets that return arrays of multiple objects.
The following basically merges the two arrays.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
$computer = 'Server01' $collection = @() $services = Get-Service | Select name, status $processes = Get-Process | Select processname, path foreach ($service in $services) { $collection += [pscustomobject] @{ ServiceName = $service.name ServiceStatus = $service.status ProcessName = "" ProcessPath = "" } } foreach ($process in $processes) { $collection += [pscustomobject] @{ ServiceName = "" ServiceStatus = "" ProcessName = $process.processname ProcessPath = $process.path } } $collection |
Personally, I’d just use the two lines for $services
and $processes
and be done.