Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading a PowerShell hashtable from a file?

Tags:

powershell

I've got a file containing some data in PowerShell Object Notation:

@{ X = 'x'; Y = 'y' }

I'd like to load this into a variable from the file.

like image 458
Roger Lipscombe Avatar asked May 24 '12 19:05

Roger Lipscombe


2 Answers

(I figured it out while putting together a repro)

PS> $content = ( Get-Content .\foo.pson | Out-String )
PS> $data = ( Invoke-Expression $content )

Get-Content returns an array with the lines in the file; the Out-String is used to join them together.

Invoke-Expression then runs the script, and the result is captured. This is open to injection attacks, but that's OK in my specific case.

Or, if you prefer your PowerShell terse:

PS> $data = gc .\foo.pson | Out-String | iex

(I can't find a shorter form of Out-String)

like image 67
Roger Lipscombe Avatar answered Nov 12 '22 20:11

Roger Lipscombe


I've used ConvertFrom-StringData. If you want to use this approach you'll need to change the way you store key/value pairs with each on its own line and no quotes:

#Contents of test.txt
X = x
Y = y

get-content .\test.txt | ConvertFrom-StringData

Name                           Value
----                           -----
X                              x
Y                              y

ConvertFrom-StringData is a built-in cmdlet. I created corresponding ConvertTo-StringData function available here http://poshcode.org/1986

like image 12
Chad Miller Avatar answered Nov 12 '22 20:11

Chad Miller