2013-08-26 31 views
4

我想通過參數傳入的名稱引用哈希表。使用變量來引用哈希表的內容

Ex。

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 

} 

是否有另一種方式來這樣做是爲了獲得這些價值?有沒有更好的方法,而不是使用哈希表?任何幫助,將不勝感激。

+1

運行此代碼時,您不知道語法錯誤嗎?哈希表文字是 = ... – BartekB

+1

修復了OP的語法錯誤。 – dugas

回答

3

是否有另一種方式來這樣做是爲了獲得這些價值?

是的,你可能使用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的解決方案是一個更好的方法來實現你的目標的好建議。

+0

謝謝!這對我來說很有效,因爲我正在處理代碼中其他地方的所有異常。 – tylerauerbeck

6

我可能會用哈希散列去:

param (
    [string[]]$Specify 
) 

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