dharmatech
dharmatech

Reputation: 9527

Print hash table as literal

Let's say I have a hash table in a variable:

$tbl = @{ abc = 100; def = 200 }

Is there a way to print it out such that it's a valid PowerShell hash table literal?

Upvotes: 2

Views: 711

Answers (2)

Emperor XLII
Emperor XLII

Reputation: 13432

Here is a simple function to handle hashtables like that given in the example:

function HashtableToString( $h ) {
  $items = @($h.GetEnumerator() | foreach { '{0} = {1}' -f $_.Key,$_.Value })
  '@{ ' + ($items -join '; ') + ' }'
}

Note that this does not handle arbitrary values (e.g. strings used as values would need to be quoted, unlike keys), but numeric values appear correctly.

Upvotes: 2

tkokasih
tkokasih

Reputation: 1188

There is no method to print the hash as literal hash, you have to create your own function to print the hash table.

Upvotes: 0

Related Questions