Does powershell have associative arrays?

孤街醉人 提交于 2019-11-29 02:52:08
Doug Finke

also

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

or

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

Yes. Use the following syntax to create them

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

Will add also the way to iterate through hashtable, as I was looking for the solution and did not found one...

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

You can also do this:

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

Not associative array, but equally as useful.

-Oisin

I use this for keeping track of sites/directories when working on multiple domains. It is possible to initialise the array when declaring it rather than adding each entry separately:

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

$url = $siteUrls[$domain]
PS C:\> $a = @{}                                                      
PS C:\> $a.gettype()                                                  

IsPublic IsSerial Name                                     BaseType            

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

True     True     Hashtable                                System.Object       

So a hashtable is an associative array. Ohhh.

Or:

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

Create From JSON String

$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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!