Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format a nested hashtable

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.

like image 674
Johnny 5 Avatar asked May 23 '15 16:05

Johnny 5


People also ask

What is a nested hash table?

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.

How do I iterate through a Hashtable in PowerShell?

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.

How do I merge two hash tables in PowerShell?

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.

How do I add values to a Hashtable in PowerShell?

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.


2 Answers

inspired by donothingsuccessfully, what about

$items | ConvertTo-Json

Looks more readable (to me)

like image 60
furicle Avatar answered Oct 21 '22 18:10

furicle


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
  }
}}
like image 41
Ansgar Wiechers Avatar answered Oct 21 '22 19:10

Ansgar Wiechers