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.
As you can probably imagine, a nested hash table is a hash table inside another one. Before we go any further, there are a few things to consider when using nested hash tables: They are not a replacement for input files or databases as data sources. E.g. xml, csv files or SQL databases.
In the first method, the one that I prefer, you can use the GetEnumerator method of the hash table object. In the second method, instead of iterating over the hash table itself, we loop over the Keys of the hash table. Both of these methods produce the same output as our original version.
Adding values of the hash table is simple as the adding string. We just need to use the addition operator (+) to merge two hash table values.
And, you can add keys and values to a hash table by using the addition operator ( + ) to add a hash table to an existing hash table. For example, the following statement adds a "Time" key with a value of "Now" to the hash table in the $hash variable. You can also add values that are stored in variables.
inspired by donothingsuccessfully, what about
$items | ConvertTo-Json
Looks more readable (to me)
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
}
}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With