powershellexport-to-csvpscustomobject

Export PSCustomObject containing HashTable to CSV


My Object is Structured like this

$ToExport = [pscustomobject]@{
           "samAccountName" = ''
           "forwarded" = @{
                "ForwardTo" = ""
                "RedirectTo" = ""
           }
}  

When i now try to export it into a CSV i achieved two things, first i recieve the samaccountname and under forwarded only System.Collections.Hashtable appears. The second possibility including

Select * -ExpandProperty "forwarded"  

now doesnt display the samAccountname in the export anymore, only the name of the forwarded object and the two objects ForwardedTo and RedirectedTO

Incase this is in any way important: The purpose of the script is to pass through all mailboxes and display all forwarding rules, thats also the reason why forwarding is a hashtable that can contain multiple entries.

Is there a possibility to get this object in a structured way into a csv or do i have to use Json or any other type of data structure?

In advance thanks for any help.


Solution

  • As suggested in the comments, one compromise is to embed JSON in the CSV:

    $flatExport = $ToExport |Select SAMAccountName,@{Name='forwarded';Expression={$_.forwarded |ConvertTo-Json -Compress}}
    $flatExport |Export-Csv -Path path\to\export.csv -NoTypeInformation
    

    This will work well if the eventual consumer of the CSV is also a PowerShell script or otherwise recognizes "" as a valid escape sequence for ".

    Otherwise you'll have to pick a serialization format better fit for hierarchical data, like exporting the whole thing to JSON for example:

    $ToExport |ConvertTo-Json -Compress |Set-Content export.json