Powershell: Custom object to CSV

时间:2016-03-04 17:47:25

标签: csv powershell object

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?

1 个答案:

答案 0 :(得分:2)

您没有创建对象,您创建了一个有序字典。字典不能直接导出为CSV,因为它是一个包含多个键值条目的单个对象。

var ref = Firebase(DataService.dataService.USERS_REF)

ref.observeEventType(.ChildChanged, withBlock: { snapshot in
    println("the changed user is: \(snapshot.value)")
})

要导出字典,您需要使用([ordered]@{}).GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True OrderedDictionary System.Object 逐个获取对象,这将产生此CSV:

GetEnumerator()

如果您想要单个对象,请使用$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" 将属性的哈希表强制转换为PSObject

[pscustomobject]@{}

或者如果你正在使用PS 1.0或2.0:

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

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