调用哈希表时命令中的变量 [英] Variables in command when calling hashtable
问题描述
我正在尝试从像下面的哈希表中获取一个值.
I'm trying to fetch a value from a hashtable like the one below.
$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
可以很好地工作,但是由于这将是针对几种不同类型的数据(和环境)的通用脚本,因此我在调用哈希表(例如下面的表)时希望包含多个变量.
It's working fine if I use $Hashtable1AuthTestID.BID_XPI
but since this will be a generic script for several different type of data (and environments) I would like to include several variable when I call the hashtable such as the one below.
# 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))中获得实际值.
I've tested several different approaches but can't get it working. I do get the correct syntax (if I print the values from the variables) such as $Hashtable1AuthTestID.BID_XPI
but I don't get the actual value from the hashtable ((id 2)).
推荐答案
通过使用另一个变量的名称(尽管可能)引用单独命名的变量是一种错误的方法.不要这样处理这种情况的规范方法是,如果要按索引访问数据结构或对象,则使用数组:
Referencing individually named variables by using a name from another variable -although possible- is a misguided approach. Don't do it. The canonical way of dealing with situations like this is to use either an array, if you want to access the data structure or object by index:
$hashtables = @()
$hashtables += @{
"BID_XPI" = "(id 2)"
"MBID_XPI" = "(id 3)"
...
}
$hashtables[0].MBID_XPI
或哈希表(如果要按名称访问数据结构或对象)
or a hashtable, if you want to access the data structure or object by name:
$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
这篇关于调用哈希表时命令中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!