9

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.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Johnny 5
  • 499
  • 5
  • 10
  • Worth noting: [This answer](https://stackoverflow.com/a/24854277/7571258) from the question [Save hash table in PowerShell object notation (PSON)](https://stackoverflow.com/questions/15139552/save-hash-table-in-powershell-object-notation-pson) – zett42 Jan 23 '19 at 16:09

3 Answers3

12

inspired by donothingsuccessfully, what about

$items | ConvertTo-Json

Looks more readable (to me)

furicle
  • 1,197
  • 1
  • 9
  • 10
  • Not just more readable, probably more efficient and most importantly can work with arbitrary depth (via the `Depth` argument). – Ohad Schneider Mar 03 '19 at 23:18
8

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
  }
}}
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
2

It's not pretty but ConvertTo-Xml -As String can display nested data structures to an arbitrary depth:

$items | ConvertTo-Xml -As String