使用变量来引用哈希表的内容

tyl*_*eck 5 variables powershell hashtable

我正在尝试通过参数传递的名称来引用哈希表.

防爆.

TestScript.Ps1 -specify TestDomain1,TestDomain2
Run Code Online (Sandbox Code Playgroud)

TestScript.ps1的内容:

param(
    [string[]]$specify
)


$TestDomain1 = @{"Name" = "Test1", "Hour" = 1}
$TestDomain2 = @{"Name" = "Test2", "Hour" = 2}

foreach($a in $specify)
{
    write-host $($a).Name
    #This is where I would expect it to return the Name value contained in the respective
    # hash table. However when I do this, nothing is being returned

}
Run Code Online (Sandbox Code Playgroud)

还有另一种方法可以做到这一点来获得这些价值吗?有没有更好的方法而不是使用哈希表?任何帮助,将不胜感激.

Bar*_*ekB 6

我可能会使用哈希哈希:

param (
    [string[]]$Specify
)

$Options = @{
    TestDomain1 = @{
        Name = 'Test1'
        Hour = 1
    }
    TestDomain2 = @{
        Name = 'Test2'
        Hour = 2
    }
}
foreach ($a in $Specify) {
    $Options.$a.Name
}
Run Code Online (Sandbox Code Playgroud)


dug*_*gas 4

还有另一种方法可以做到这一点来获取这些值吗?

是的,您可以使用 Get-Variable cmdlet。

param(
[string[]]$Specify
)

$TestDomain1 = @{"Name" = "Test1"; "Hour" = 1}
$TestDomain2 = @{"Name" = "Test2"; "Hour" = 2}

foreach($a in $specify)
{
 $hashtable = Get-Variable $a
 write-host $hashtable.Value.Name
 #This is where I would expect it to return the Name value contained in the respective
 # hash table. However when I do this, nothing is being returned
}
Run Code Online (Sandbox Code Playgroud)

除了使用哈希表之外,还有更好的方法吗?

使用哈希表并不是什么大问题,而是通过输入定义的名称来引用变量。如果传递指定参数的内容使用了引用您不想访问的变量的字符串怎么办?@BartekB 的解决方案是实现目标的更好方法的一个很好的建议。