Powershell:自定义对象到 CSV

the*_*zik 0 csv powershell object

我创建了自定义对象,它基本上在其键中存储日期和一些整数:

$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;
}
Run Code Online (Sandbox Code Playgroud)

我需要将其输出到 CSV 文件,以便每个值都写入新列中。我尝试使用,$data | export-csv dump.csv 但我的 CSV 看起来像这样:

#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"
Run Code Online (Sandbox Code Playgroud)

离我想要达到的目标还差得很远。如何让一些东西更接近:

date,testers,stnofeedback....
04-03-2016,2031,1021....
Run Code Online (Sandbox Code Playgroud)

我创建了该对象,因为应该很容易将其导出为 csv。也许有完全不同的、更好的方法?或者我的对象缺少什么?

Fro*_* F. 6

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

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

IsPublic IsSerial Name              BaseType     
-------- -------- ----              --------     
True     True     OrderedDictionary System.Object
Run Code Online (Sandbox Code Playgroud)

要导出字典,您需要使用它GetEnumerator()来逐一获取对象,这将生成以下 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"
Run Code Online (Sandbox Code Playgroud)

如果您想要单个对象,请将属性的哈希表转换为PSObjectusing [pscustomobject]@{}

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

$data | ConvertTo-Csv -NoTypeInformation
"Date","Testers"
"04-03-2016","Hello world"
Run Code Online (Sandbox Code Playgroud)

或者,如果您使用 PS 1.0 或 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"
Run Code Online (Sandbox Code Playgroud)