Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

powershell

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
like image 612
John Tabs Avatar asked Dec 26 '22 10:12

John Tabs


2 Answers

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

  • PowerShell Code Smell: Invoke-Expression (and some suggestions)
  • Invoke-Expression considered harmful

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.

like image 106
gerard Avatar answered Dec 29 '22 01:12

gerard


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
like image 21
John Tabs Avatar answered Dec 28 '22 23:12

John Tabs