Nimai
Nimai

Reputation: 783

How can I print a PowerShell hash object as a hash object?

If I have a PowerShell hash object, how can I output it's contents in a format that can be used to declare a PowerShell hash object literal?

As a simple example, say you initialize a variable $x as follows:

$x = @{
  a = 1
  b = 2
  c = @{
    foo = "bar"
  }
}

If you just enter $x you'll get a tabular view:

Name                           Value                                                                                                        
----                           -----                                                                                                        
c                              {foo}                                                                                                        
b                              2                                                                                                            
a                              1                                                                                                            

I know there are other formatters, but I didn't find one that formats it back out as a pretty-printed PowerShell literal, something like how I declared it above.

Upvotes: 4

Views: 534

Answers (2)

iRon
iRon

Reputation: 23663

This ConvertTo-Expression cmdlet can serialize most (recursive) objects to a PowerShell expression:

$x | ConvertTo-Expression
@{
        'c' = @{'foo' = 'bar'}
        'b' = 2
        'a' = 1
}

Upvotes: 4

AdminOfThings
AdminOfThings

Reputation: 25001

I'm not sure if this is what you had in mind, but you could always declare your variable as a scriptblock using the {} notation. Then you can call (&) the scriptblock when you want a hashtable output. So when you enter $x, you can preserve your original formatting.

# Declaration
$x = {@{
a = 1
b = 2
c = @{
  foo = "bar"
}
}}

#Retrieval of $x contents
$x
@{
a = 1
b = 2
c = @{
  foo = "bar"
}
}

# Calling the scriptblock
& $x

Name                           Value
----                           -----
c                              {foo}
b                              2
a                              1

Upvotes: 0

Related Questions