【问题标题】:Use variable to refer to contents of hash table使用变量来引用哈希表的内容
【发布时间】:2013-08-29 07:53:55
【问题描述】:

我正在尝试按名称引用通过参数传入的哈希表。

例如

TestScript.Ps1 -specify TestDomain1,TestDomain2

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

}

还有其他方法可以获取这些值吗?有没有比使用哈希表更好的方法?任何帮助将不胜感激。

【问题讨论】:

  • 运行此代码时不会出现语法错误吗?哈希表文字是 = ...
  • 修复了 OP 的语法错误。

标签: variables powershell hashtable


【解决方案1】:

我可能会选择散列的散列:

param (
    [string[]]$Specify
)

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

【讨论】:

    【解决方案2】:

    还有其他方法可以获取这些值吗?

    是的,您可以使用 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
    }
    

    有没有比使用哈希表更好的方法?

    使用哈希表与其说是通过输入定义的名称来引用变量那样有问题。如果传递指定参数的东西使用的字符串引用了您不想访问的变量怎么办? @BartekB 的解决方案是一个很好的建议,可以更好地实现您的目标。

    【讨论】:

    • 谢谢!这对我有用,因为我正在处理代码中其他地方的所有异常。
    猜你喜欢
    • 2013-03-21
    • 2018-04-02
    • 2014-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多