theadzik
theadzik

Reputation: 138

Powershell: Custom object to CSV

I created custom object that basically stores Date and few integers in it's keys:

$data = [Ordered]@{
    "Date" = $currentdate.ToString('dd-MM-yyyy');
    "Testers" = $totalTesterCount;
    "StNoFeedback" = $tester_status.NoFeedback;
    "StNotSolved" = $tester_status.NotSolved;
    "StSolved" = $tester_status.Solved;
    "StNoIssues" = $tester_status.NoIssues;
    "OSNoFeedback" = $tester_os.NoFeedback;
    "OSW7" = $tester_os.W7;
    "OSW10" = $tester_os.W10;
    "OfficeNoFeedback" =  $tester_Office.NoFeedback;
    "OfficeO10" = $tester_Office.O10;
    "OfficeO13" = $tester_Office.O13;
    "OfficeO16" = $tester_Office.O16;
}

I need to Output it to CSV file in a way that every value is written in new column. I tried using $data | export-csv dump.csv but my CSV looks like that:

#TYPE System.Collections.Specialized.OrderedDictionary
"Count","IsReadOnly","Keys","Values","IsFixedSize","SyncRoot","IsSynchronized"
"13","False","System.Collections.Specialized.OrderedDictionary+OrderedDictionaryKeyValueCollection","System.Collections.Specialized.OrderedDictionary+OrderedDictionaryKeyValueCollection","False","System.Object","False"

Not even close to what I want to achieve. How to get something closer to:

date,testers,stnofeedback....
04-03-2016,2031,1021....

I created the object because it was supposed to be easy to export it as csv. Maybe there is entirely different, better approach? Or is my object lacking something?

Upvotes: 0

Views: 11199

Answers (1)

Frode F.
Frode F.

Reputation: 54821

You didn't create an object, you created an ordered dictionary. A dictionary can't be exported to CSV-directly as it's a single object which holds multiple key-value-entries.

([ordered]@{}).GetType()

IsPublic IsSerial Name              BaseType     
-------- -------- ----              --------     
True     True     OrderedDictionary System.Object

To export a dictionary you need to use GetEnumerator() to get the objects one by one, which would result in this CSV:

$data = [Ordered]@{
    "Date" = (get-date).ToString('dd-MM-yyyy')
    "Testers" = "Hello world"
}

$data.GetEnumerator() | ConvertTo-Csv -NoTypeInformation
"Name","Key","Value"
"Date","Date","04-03-2016"
"Testers","Testers","Hello world"

If you want a single object, cast the hashtable of properties to a PSObject using [pscustomobject]@{}.

$data = [pscustomobject]@{
    "Date" = (get-date).ToString('dd-MM-yyyy')
    "Testers" = "Hello world"
}

$data | ConvertTo-Csv -NoTypeInformation
"Date","Testers"
"04-03-2016","Hello world"

Or if you're using PS 1.0 or 2.0:

$data = New-Object -TypeName psobject -Property @{
    "Date" = (get-date).ToString('dd-MM-yyyy')
    "Testers" = "Hello world"
}

$data | ConvertTo-Csv -NoTypeInformation
"Testers","Date"
"Hello world","04-03-2016"

Upvotes: 6

Related Questions