我想问您有关哈希表(powershell)中的动态嵌套键的问题。我已经做过一些研究,但找不到答案。
# 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
我将不胜感激,在此先感谢您。
这将起作用,但是我不确定,如果这是解决方案,那么您正在寻找
$Hashtable.$(($MainAndSubcategory -split '\.')[0]).$(($MainAndSubcategory -split '\.')[1]).myproperty
与将maincategory和subcategory键放入单独的变量中相同
可以构建一个字符串,然后使用Invoke-Expression
执行它。请注意,初始的$
字符已转义。
$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"