Search code examples
powershelldynamicpathkeyhashtable

powershell hashtable dynamic key


I would like to ask you about dynamic nested keys in hashtables (powershell). I 've already done some research and I can't find an answer.

# I got this hash structure, works fine
$Hashtable                                              = @{}
$Hashtable.Maincategory                             = @{}
$Hashtable.Maincategory.Subcategory                 = @{}
$Hashtable.Maincategory.Subcategory.MyProperty          = @{ 'property' = 'value'}
$Hashtable.Maincategory.Subcategory.MyProperty

Name                           Value
----                           -----
property                       value



# I want dynamic path to my property
$MainAndSubCategory                                                                = [string]'Maincategory.Subcategory'
$Hashtable.$MainAndSubCategory.MyProperty                                               # doesn't work
$Hashtable."$MainAndSubCategory".MyProperty                                         # doesn't work
$Hashtable."$($MainAndSubCategory)".MyProperty                                       # doesn't work
$Hashtable."$(Get-Variable -Name 'MainAndSubCategory' -ValueOnly)".MyProperty           # doesn't work

I would appreciate advice, thanks in advance.


Solution

  • It is possible to build a string, then execute it using Invoke-Expression. Note that the initial $ character is escaped.

    $Hashtable                                     = @{}
    $Hashtable.Maincategory                        = @{}
    $Hashtable.Maincategory.Subcategory            = @{}
    $Hashtable.Maincategory.Subcategory.MyProperty = @{ 'property' = 'value'}
    $Hashtable.Maincategory.Subcategory.MyProperty
    
    $MainAndSubCategory = 'Maincategory.Subcategory'
    Invoke-Expression -Command "`$Hashtable.$MainAndSubCategory.MyProperty"
    

    One thing to be careful about is that anything that could set the value of the string would be able to inject unwanted code.