powershell有关联数组吗?

Geo*_*uer 31 arrays powershell associative-array

我正在编写一个返回id,name对的函数.

我想做点什么

$a = get-name-id-pair()
$a.Id
$a.Name
Run Code Online (Sandbox Code Playgroud)

喜欢在javascript中可能.或至少

$a = get-name-id-pair()
$a["id"]
$a["name"]
Run Code Online (Sandbox Code Playgroud)

喜欢在PHP中可能.我可以用PowerShell做到吗?

Dou*_*nke 51

$a = @{'foo'='bar'}
Run Code Online (Sandbox Code Playgroud)

要么

$a = @{}
$a.foo = 'bar'
Run Code Online (Sandbox Code Playgroud)

  • $ associativeArray = @ {Jane = 1 Tom = 2 Harry = 3} foreach($ keyword in $ associativeArray.Keys){$ key} foreach($ associativeArray.GetEnumerator()中的$ item){"{0} = {1} "-f $ item.Key,$ item.Value}×注释的长度必须至少为15个字符.×注释的长度必须至少为15个字符.×注释的长度必须至少为15个字符. (4认同)
  • 旧评论,但你如何通过foreach循环遍历关联数组? (2认同)

Jar*_*Par 23

是.使用以下语法创建它们

$a = @{}
$a["foo"] = "bar"
Run Code Online (Sandbox Code Playgroud)


Iva*_*nko 12

将添加迭代哈希表的方式,因为我正在寻找解决方案,但没有找到一个...

$c = @{"1"="one";"2"="two"} 
foreach($g in $c.Keys){write-host $c[$g]} #where key = $g and value = $c[$g]
Run Code Online (Sandbox Code Playgroud)

  • 唯一提到分号“;”分隔符的答案。 (2认同)

Jos*_*hua 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
Run Code Online (Sandbox Code Playgroud)