我正在编写一个返回id,name对的函数。
我想做点什么
$a = get-name-id-pair()
$a.Id
$a.Name
喜欢在javascript中可能。或者至少
$a = get-name-id-pair()
$a["id"]
$a["name"]
像在php中可能的那样。我能用PowerShell做到吗?
答案 0 :(得分:51)
也
$a = @{'foo'='bar'}
或
$a = @{}
$a.foo = 'bar'
答案 1 :(得分:22)
是。使用以下语法创建它们
$a = @{}
$a["foo"] = "bar"
答案 2 :(得分:11)
还会添加迭代哈希表的方法,因为我正在寻找解决方案而没有找到一个......
$c = @{"1"="one";"2"="two"}
foreach($g in $c.Keys){write-host $c[$g]} #where key = $g and value = $c[$g]
答案 3 :(得分:9)
#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
答案 4 :(得分:2)
PS C:\> $a = @{}
PS C:\> $a.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Hashtable System.Object
因此哈希表是一个关联数组。哦~~。
或者:
PS C:\> $a = [Collections.Hashtable]::new()
答案 5 :(得分:1)
你也可以这样做:
function get-faqentry { "meaning of life?", 42 }
$q, $a = get-faqentry
不是关联数组,但同样有用。
-Oisin
答案 6 :(得分:1)
我在处理多个域时使用它来跟踪站点/目录。在声明数组时可以初始化数组,而不是单独添加每个条目:
$domain = $env:userdnsdomain
$siteUrls = @{ 'TEST' = 'http://test/SystemCentre'
'LIVE' = 'http://live/SystemCentre' }
$url = $siteUrls[$domain]
答案 7 :(得分:1)
从JSON字符串创建
$people= '[
{
"name":"John",
"phone":"(555) 555-5555"
},{
"name":"Mary",
"phone":"(444) 444-4444"
}
]';
# Convert String To Powershell Array
$people_obj = ConvertFrom-Json -InputObject $people;
# Loop through them and get each value by key.
Foreach($person in $people_obj ) {
echo $person.name;
}