是否有PowerShell的关联数组?(Does powershell have associati

2019-07-20 11:00发布

我写返回一个ID,名称对一个功能。

我想这样做

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

就像有可能在JavaScript。 或至少

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

就像有可能在PHP。 我能做到这一点使用PowerShell?

Answer 1:

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

要么

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


Answer 2:

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

$a = @{}
$a["foo"] = "bar"


Answer 3:

还将通过增加哈希表进行迭代,因为我一直在寻找解决方案,并没有找到一个方式......

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


Answer 4:

#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


Answer 5:

PS C:\> $a = @{}                                                      
PS C:\> $a.gettype()                                                  

IsPublic IsSerial Name                                     BaseType            

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

True     True     Hashtable                                System.Object       

所以散列表是一个关联数组。 噢噢噢。

要么:

PS C:\> $a = [Collections.Hashtable]::new()


Answer 6:

你也可以这样做:

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

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

-Oisin



Answer 7:

我用这个跟踪的网站/目录工作的多个域的时候。 这是可能声明它时,而不是分别添加每个条目初始化数组:

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

$url = $siteUrls[$domain]


Answer 8:

创建从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;
}


文章来源: Does powershell have associative arrays?