调用哈希表时命令中的变量

Variables in command when calling hashtable

我正在尝试从如下所示的哈希表中获取一个值。

$Hashtable1AuthTestID = @{ 
    "BID_XPI" = "(id 2)";
    "MBID_XPI" = "(id 3)";
    "T_XPI" = "(id 4)";
    "ST_XPI" = "(id 5)";
    "SI_XPI" = "(id 6)";
    "T_SAML" = "(id 7)";
    "ST_SAML" = "(id 8)";
    "SI_SAML" = "(id 9)";
    "BID_SAML" = "(id 10)";
    "MBID_SAML" = "(id 11)";
}

如果我使用 $Hashtable1AuthTestID.BID_XPI 它工作正常但是因为这将是几种不同类型的数据(和环境)的通用脚本我想在调用哈希表时包含几个变量,例如下面。

# Without variables (Example): $Hashtable1AuthTestID.BID_XPI 
# With variables (Example): $<Hashtable><Type><Environment>.<Method>

$hashtable = "Hashtable1"
$type = "Auth"
$environment = "Test"
$method = "BID_XPI"
# ID is the example is a string.

$'$hashtable1'$environment"ID".$method
$$hashtable1$environment+"ID".$method

我测试了几种不同的方法,但无法正常工作。我确实得到了正确的语法(如果我从变量中打印值),例如 $Hashtable1AuthTestID.BID_XPI 但我没有从哈希表 ((id 2)).

中得到实际值

你可以使用 Get-Variable:

$hashtable = "Hashtable1"
$type = "Auth"
$environment = "Test"
$method = "BID_XPI"

(Get-Variable -Name "$($hashtable)$($type)$($environment)ID".).Value.$method

通过使用来自另一个变量的名称来引用单独命名的变量 - 尽管可能 - 是一种误入歧途的方法。不要这样做。处理这种情况的规范方法是使用数组,如果你想通过索引访问数据结构或对象:

$hashtables = @()
$hashtables += @{
    "BID_XPI"  = "(id 2)"
    "MBID_XPI" = "(id 3)"
    ...
}

$hashtables[0].MBID_XPI

或哈希表,如果您想按名称访问数据结构或对象:

$hashtables = @{}
$hashtables['Hashtable1AuthTestID'] = @{
    "BID_XPI"  = "(id 2)"
    "MBID_XPI" = "(id 3)"
    ...
}

$hashtable   = 'Hashtable1'
$type        = 'Auth'
$environment = 'Test'
$method      = 'BID_XPI'

$name = "${hashtable}${type}${environment}ID"

$hashtables.$name.$method

为了完整起见,这里介绍了如何使用另一个变量的名称来获取变量,但同样,不推荐这样做。

$Hashtable1AuthTestID = @{
    "BID_XPI"  = "(id 2)"
    "MBID_XPI" = "(id 3)"
    ...
}

$hashtable   = 'Hashtable1'
$type        = 'Auth'
$environment = 'Test'
$method      = 'BID_XPI'

$name = "${hashtable}${type}${environment}ID"

(Get-Variable -Name $name -ValueOnly).$method

如果您能够打印它,您可以调用它:

$string = '[=10=]{1}{2}ID.{3}' -f $hashtable,$type,$environment,$method
Invoke-Expression -Command $string