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

时间:2019-06-17 07:44:35

标签: powershell 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))中获得实际值。

3 个答案:

答案 0 :(得分:1)

使用另一个变量的名称(尽管可能)引用单独命名的变量是一种误导的方法。不要这样处理此类情况的规范方法是,如果要按索引访问数据结构或对象,则使用数组:

$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

答案 1 :(得分:0)

您可以使用Get-Variable

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

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

答案 2 :(得分:0)

如果可以打印,则可以调用它:

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