我在寫一個返回一個id,name對的函數。PowerShell有關聯數組嗎?
我想這樣做
$a = get-name-id-pair()
$a.Id
$a.Name
喜歡在JavaScript中是可能的。或至少
$a = get-name-id-pair()
$a["id"]
$a["name"]
像是可能在PHP中。我可以用PowerShell來做到嗎?
我在寫一個返回一個id,name對的函數。PowerShell有關聯數組嗎?
我想這樣做
$a = get-name-id-pair()
$a.Id
$a.Name
喜歡在JavaScript中是可能的。或至少
$a = get-name-id-pair()
$a["id"]
$a["name"]
像是可能在PHP中。我可以用PowerShell來做到嗎?
也
$a = @{'foo'='bar'}
或
$a = @{}
$a.foo = 'bar'
是的。使用下面的語法來創建它們
$a = @{}
$a["foo"] = "bar"
你也可以這樣做:
function get-faqentry { "meaning of life?", 42 }
$q, $a = get-faqentry
不關聯數組,但同樣有用。
-Oisin
#Define an empty hash
$i = @{}
#Define entries in hash as a number/value pair - ie. number 12345 paired with Mike is entered as $hash[number] = 'value'
$i['12345'] = 'Mike'
$i['23456'] = 'Henry'
$i['34567'] = 'Dave'
$i['45678'] = 'Anne'
$i['56789'] = 'Mary'
#(optional, depending on what you're trying to do) call value pair from hash table as a variable of your choosing
$x = $i['12345']
#Display the value of the variable you defined
$x
#If you entered everything as above, value returned would be:
Mike
我用這個跟蹤的網站/目錄多個域上工作時。這是可能宣佈它的時候,而不是單獨添加的每個條目初始化數組:
$domain = $env:userdnsdomain
$siteUrls = @{ 'TEST' = 'http://test/SystemCentre'
'LIVE' = 'http://live/SystemCentre' }
$url = $siteUrls[$domain]
也將增加的方式,通過哈希表進行迭代,因爲我一直在尋找解決方案,並沒有找到一個...
$c = @{"1"="one";"2"="two"}
foreach($g in $c.Keys){write-host $c[$g]} #where key = $g and value = $c[$g]
PS C:\> $a = @{}
PS C:\> $a.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Hashtable System.Object
所以散列表是一個關聯數組。噢噢噢。
或者:
PS C:\> $a = [Collections.Hashtable]::new()
舊發表評論,但你會如何遍歷通過foreach循環的關聯數組? – 2013-12-18 16:00:48
$關聯數組= @ { 簡= 1 湯姆= 2 哈利= 3 } 的foreach(在$ $ associativeArray.Keys鍵){$ 鍵 } 的foreach($ $在項(0)= {1}「-f $ item.Key,$ item.Value }×註釋必須至少包含15個字符×註釋必須至少包含15個字符長度×註釋必須至少包含15個字符。 – 2013-12-19 14:34:22