37

我正在编写一个返回 id、name 对的函数。

我想做类似的事情

$a = get-name-id-pair()
$a.Id
$a.Name

像在javascript中是可能的。或者至少

$a = get-name-id-pair()
$a["id"]
$a["name"]

像在 php 中是可能的。我可以用powershell做到这一点吗?

4

8 回答 8

55

$a = @{'foo'='bar'}

或者

$a = @{}
$a.foo = 'bar'
于 2009-10-02T01:55:37.153 回答
25

是的。使用以下语法创建它们

$a = @{}
$a["foo"] = "bar"
于 2009-10-01T19:48:45.583 回答
20

还将添加遍历哈希表的方法,因为我正在寻找解决方案但没有找到...

$c = @{"1"="one";"2"="two"} 
foreach($g in $c.Keys){write-host $c[$g]} #where key = $g and value = $c[$g]
于 2017-01-22T11:37:35.460 回答
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
于 2010-09-09T06:35:03.103 回答
2

在处理多个域时,我使用它来跟踪站点/目录。可以在声明数组时初始化数组,而不是单独添加每个条目:

$domain = $env:userdnsdomain
$siteUrls = @{ 'TEST' = 'http://test/SystemCentre' 
               'LIVE' = 'http://live/SystemCentre' }

$url = $siteUrls[$domain]
于 2015-05-05T23:07:31.533 回答
2
PS C:\> $a = @{}                                                      
PS C:\> $a.gettype()                                                  

IsPublic IsSerial Name                                     BaseType            

-------- -------- ----                                     --------            

True     True     Hashtable                                System.Object       

所以哈希表是一个关联数组。哦。

或者:

PS C:\> $a = [Collections.Hashtable]::new()
于 2017-07-24T04:15:07.447 回答
2

从 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;
}
于 2018-05-15T06:52:47.680 回答
1

你也可以这样做:

function get-faqentry { "meaning of life?", 42 }
$q, $a = get-faqentry 

不是关联数组,但同样有用。

-Oisin

于 2009-10-03T15:10:02.673 回答