Exporting multiple PSCustomObject s to a single CSV

1.2k Views Asked by At

I have 2 PScustomObjects that i would like to combine into a single csv as follows:

 $Output1 = [PSCustomObject]@{
            Timestamp1 = (Get-Date)
            InstanceName1 = $ProcessName1
            Count1 = $Processes1.Count
            Memory1 = $MEMLoad1
            CPU1 = $CPULoad1
        } 
        $Output2 = [PSCustomObject]@{
            Timestamp2 = (Get-Date)
            InstanceName2 = $ProcessName2
            Count2 = $Processes2.Count
            Memory2 = $MEMLoad2
            CPU2 = $CPULoad2
        } 

The CSV should have the titles TimeStamp1, InstanceName1......TimeStamp2, InstanceName2.... This code runs in a loop and exports data each pass.

Is there a way to do this? Also is there a way to do this dynamically to avoid replicating large amounts of code if i am to export data on say 100 PsCustomObjects, maybe lookping through the input data for the object and the putting in in one object and passing that to the csv while dynamically changing titles?

I use the following line to export. I've tried -InputObject $Output1, $Output2 but that gives gibberish.

Export-Csv -InputObject $Output1 -path $Path1 -NoTypeInformation -Append -Force 

The only solution i have so far is to export multiple CSV's but that gets bulky fast.

Any help is greatly appreciated!

1

There are 1 best solutions below

0
On

The best solution is to ensure all the objects your script/function outputs use the same schema (that is, they should all share the same common property names).

If that's not possible, you can use Select-Object to ensure all possible properties are selected for all objects:

$Output1,$Output2 |Select-Object Count1,Count2,CPU1,CPU2,InstanceName1,InstanceName2,Memory1,Memory2,Timestamp1,Timestamp2 |Export-Csv ...

This is obviously not very practical, so if you have many different object schemas, you'll want to automate the discovery of all possible property names.

To do that, we can inspect the psobject hidden memberset:

$allTheObjectsToExport = $Output1,$Output2

$propertyNames = $allTheObjectsToExport |ForEach-Object {
  # Discover all the object's properties
  $_.psobject.Properties |ForEach-Object {
    # Get each property name
    $_.Name
  }
} |Sort-Object -Unique

# Now the CSV will have a column for every single unique property name
$allTheObjectsToExport |Select-Object $propertyNames |Export-Csv -Path $Path1 -NoTypeInformation