代码之家  ›  专栏  ›  技术社区  ›  Ralf_Reddings

是否可以通过变量引用psObject/Hashtable名称?复制

  •  2
  • Ralf_Reddings  · 技术社区  · 2 周前

    比方说,我有很多对象(在pscustomObject或Hashtables中),我需要动态引用它们,因为用户决定访问什么数据。

    ....
    $sweden = [PSCustomObject]@{monday = "sunny" ; tuesday = "sunny" ; wednesday = "sunny" ; thursday = "sunny" ; friday = "sunny"}
    $siberia    = [PSCustomObject]@{monday = "cold" ; tuesday = "cold" ; wednesday = "cold" ; thursday = "cold" ; friday = "cold"}
    $turkey = [PSCustomObject]@{monday = "unknown" ; tuesday = "unknown" ; wednesday = "cold" ; thursday = "cold" ; friday = "cold"}
    $england = [PSCustomObject]@{monday = "miserable" ; tuesday = "miserable" ; wednesday = "miserable" ; thursday = "miserable" ; friday = "miserable"}
    ....
    

    用户将其值传递给 $country 变量,然后我需要访问相应的数据池。如下所示:

    $country = 'england'
    $("$country").monday #this should print "miserable"
    

    运行以上操作,不会发生任何事情,也不会出现任何错误。提示返回,就是这样。我也尝试过不带引号的操作, $($country).monday .

    pwsh 7.4/win11

    1 回复  |  直到 2 周前
        1
  •  4
  •   Santiago Squarzon    2 周前

    使用单个哈希表而不是多个变量来引用您的国家/地区:

    $countries = @{
        sweden  = [PSCustomObject]@{monday = 'sunny' ; tuesday = 'sunny' ; wednesday = 'sunny' ; thursday = 'sunny' ; friday = 'sunny' }
        siberia = [PSCustomObject]@{monday = 'cold' ; tuesday = 'cold' ; wednesday = 'cold' ; thursday = 'cold' ; friday = 'cold' }
        turkey  = [PSCustomObject]@{monday = 'unknown' ; tuesday = 'unknown' ; wednesday = 'cold' ; thursday = 'cold' ; friday = 'cold' }
        england = [PSCustomObject]@{monday = 'miserable' ; tuesday = 'miserable' ; wednesday = 'miserable' ; thursday = 'miserable' ; friday = 'miserable' }
    }
    
    $country = 'england'
    $countries[$country].monday # this should print "miserable"
    

    如果使用多个变量来动态引用它,则可以使用 Get-Variable , 真的很痛苦 :

    $country = 'england'
    (Get-Variable $country -ValueOnly).monday