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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With