说我同意
$d = @{"foo"="bar"; "baz"=99.9}
ConvertTo-csv $d
我希望是这样的
foo,baz
"bar",99.9
但我得到的却是:
#TYPE System.Collections.Hashtable
"IsReadOnly","IsFixedSize","IsSynchronized","Keys","Values","SyncRoot","Count"
"False","False","False","System.Collections.Hashtable+KeyCollection","System.Collections.Hashtable+ValueCollection","System.Object","2"
它似乎将有关对象的元数据放入 CSV,而不是对象的实际内容。
我怎样才能得到我预期的结果?
答案1
$d
是一个带有键(名称)/值对的哈希表,
要转换首先使其成为一个对象[PSCustomObject]
PS> $d
Name Value
---- -----
baz 99,9
foo bar
PS> [PSCustomObject]$d
baz foo
--- ---
99,9 bar
然后ConvertTo-Csv
使用参数-NoTypeInformation
PS> [PSCustomObject]$d|ConvertTo-Csv -NoTypeInformation
"baz","foo"
"99,9","bar"
为了保持初始顺序,请使用有序哈希表
PS> $d = [ordered]@{"foo"="bar"; "baz"=99.9}
PS> [PSCustomObject]$d|ConvertTo-Csv -NoTypeInformation
"foo","baz"
"bar","99,9"