John Tabs
John Tabs

Reputation: 361

Is there a way to convert a powershell string into a hashtable?

Is there is any way to tell powershell to construct a hashtable from a string that's formatted using the normal syntax for creating hashtables inline?

For example, is there any way to do something like:

$fooHashString = "@{key='value'}
$fooHash = TellPowershellToEvaluateSpecialStringExpressions($fooHashString)
$fooHash

Name                           Value
----                           -----
key                            value

Upvotes: 5

Views: 14665

Answers (4)

John Tabs
John Tabs

Reputation: 361

Hmm, shortly after posting this I stumbled upon the answer. I just needed to use the "Invoke-Expression" command on the string.

$fooHashString = "@{key='value'}"
$fooHash = Invoke-Expression $fooHashString
$fooHash

Name                           Value
----                           -----
key                            value

Upvotes: 6

js2010
js2010

Reputation: 27423

$fooHashString = "@{key='value'}" 
$fooHashString -replace '@{' -replace '}' -replace ';',"`n" -replace "'" |
  ConvertFrom-StringData

Name                           Value
----                           -----
key                            value

Upvotes: 0

Alex Kwitny
Alex Kwitny

Reputation: 11544

I think a better answer is here:

https://www.reddit.com/r/PowerShell/comments/2vqxpu/hashtable_string_to_hashtable_object/cokcfmq/

You would want to use ScriptBlock

Upvotes: 0

gerard
gerard

Reputation: 990

There are a number of reasons why using Invoke-Expression is considered a code smell. See the following blog posts for details of this

If you are using PowerShell version 3.0 or above an alternative approach is to use the ConvertFrom-StringData. You can find details on how to use this on the MSDN page ConvertFrom-StringData

In your case, you could use the following to create the HashTable

$HashString = "key1=value1 `n key2=value2"
ConvertFrom-StringData -StringData $HashString

Alternatively, you could generate the content within a here string like this

$HashString = @'
key1 = value1
key2 = value2
'@
ConvertFrom-StringData -StringData $HashString

Unfortunately, this won't work if you include \ within the string because the ConvertFrom-StringData CmdLet sees it as an escape character.

Upvotes: 7

Related Questions