Friday, March 22, 2024

Powershell Export-Csv for PSCustomobject which is a list of strings as property.

 example powershell customobject

$myObject = [PSCustomObject]@{
    Name     = 'Parag'
    Language = 'PowerShell'
    State    = 'Washington'
}

To export this object to csv we can use.

$myobject | Export-csv -path c:\temp\temp.csv -NoClobber -NoTypeInformation

The file will show up like this

 Name,Language,State

Parag,Powershell,Washington

But if the properties of the object are a list,i.e I know more than one languages then the file shows up as 

Name,Language,State

Parag,System.Collections.Generic.List`1[System.String],Washington

 That is because the command treats the property as an array. You can see the same behavior when you export an array.

To export this data properly we can do this.

$myobject | Select-Object Name,@{n='Language';e={$_.Language -join ' ' }},State

Now in the file we will see

 

 Name,Language,State

Parag,Powershell JavaScript,Washington

No comments:

Post a Comment