问题
Given a hashtable that contains heterogeneous data such as:
$items = @{
a = @{a1 = "A1"; a2 = "A2"; a3 = "A3" }
b = 1234
c = @{c1 = "C1"; c2 = "C2"; c3 = "C3" }
d = [DateTime]::Now
}
When I attempt to display the contents using the following:
$items | Format-Table -AutoSize
The output is:
Name Value
---- -----
c {c3, c1, c2}
d 05/23/15 11:37:56
b 1234
a {a2, a3, a1}
But how can I expand the contents of the nested hashtables so that I can see the key-value pairs such as:
Name Value
---- -----
c {c3=C3, c1=C1, c2=C2}
d 05/23/15 11:37:56
b 1234
a {a2=A2, a3=A3, a1=A1}
The exact display format of the nested key-value pairs is not super critical, I just want to see them.
回答1:
You need to expand nested hashtables yourself:
$items | Format-Table Name, @{n='Value';e={
if ($_.Value -is [Hashtable]) {
$ht = $_.Value
$a = $ht.keys | sort | % { '{0}={1}' -f $_, $ht[$_] }
'{{{0}}}' -f ($a -join ', ')
} else {
$_.Value
}
}}
回答2:
inspired by donothingsuccessfully, what about
$items | ConvertTo-Json
Looks more readable (to me)
回答3:
It's not pretty but ConvertTo-Xml -As String can display nested data structures to an arbitrary depth:
$items | ConvertTo-Xml -As String
来源:https://stackoverflow.com/questions/30415162/format-a-nested-hashtable