Does powershell have associative arrays?

前端 未结 8 762
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-16 09:25

I am writing a function that returns an id, name pair.

I would like to do something like

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

like

相关标签:
8条回答
  • 2020-12-16 09:57

    also

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

    or

    $a = @{}
    $a.foo = 'bar'
    
    0 讨论(0)
  • 2020-12-16 09:57

    You can also do this:

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

    Not associative array, but equally as useful.

    -Oisin

    0 讨论(0)
  • 2020-12-16 09:58

    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]
    
    0 讨论(0)
  • 2020-12-16 10:01

    Yes. Use the following syntax to create them

    $a = @{}
    $a["foo"] = "bar"
    
    0 讨论(0)
  • 2020-12-16 10:02
    #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
    
    0 讨论(0)
  • 2020-12-16 10:06

    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]
    
    0 讨论(0)
提交回复
热议问题