Export-Csv variable object data

Learn Expert



I'm trying to export an object in PowerShell into a CSV file.  My goal is to include all properties in the CSV file ,but find that only properties from the first object are included.  For example,




Name: "First Object"
ID:   1

Name: "Second Object"
ID:   2
Value: 123




In the example below, Export-Csv will provide a CSV that only includes the Name and ID field.  Is there a way to have Export-Csv include a super set of all properties found in all objects?

3 Replies

@Haniel Croitoru 


Would you please add a bit of code to understand exactly, maybe my bad English did not help me this time. 

Are the First Object and the Second object are independent objects or related to the same PSObject

Name="First Object"
id = "1"
Name="Second Object"
id = "2"

$PSFirstObject=New-Object -TypeName PSObject -Property $PS1stobject
$PsSecondObject=New-Object -TypeName PSObject -Property $PS2ndobject

And what you want to do is export the content of both PSObject to the same CSV ?



@farismalaeb , the two objects are in a collection of objects.



I actually needed to create a new object, iterate through all existing objects and add all members into the new object and then keep only the unique values.  Then I added this object into a new collection and all other objects after it.


# Create superset of fields
$memberColl = @()
$total = $objCollection.count
$i = 1
foreach ($obj in $objCollection)
    Write-Progress -Activity "Consolidating properties" -Status $obj.id -PercentComplete ($i*100/$total)
    $members = (Get-Member -InputObject $obj -MemberType NoteProperty | select Name)
    foreach ($m in $members)
        $memberColl += $m.Name

# create a list of all properties
$Properties = ($memberColl | sort | Select-Object -Unique)

# create a new object "co" with all the fields in them and a new object collection called completeObj
$completeObj = @() 
$co = New-Object -TypeName PSObject

# add all properties to the new collection
foreach ($p in $Properties)
    Add-Member -InputObject $co -MemberType NoteProperty -Name $p $null

$completeObj += $co

# Now add all existing objects to this new collection
foreach ($o in $objCollection)
    $completeObj += $o