37

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 is possible in javascript. Or at least

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

like is possible in php. Can I do that with powershell?

Kellen Stuart
  • 7,775
  • 7
  • 59
  • 82
George Mauer
  • 117,483
  • 131
  • 382
  • 612

8 Answers8

58

also

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

or

$a = @{}
$a.foo = 'bar'
x0n
  • 51,312
  • 7
  • 89
  • 111
Doug Finke
  • 6,675
  • 1
  • 31
  • 47
  • 2
    Old comment, but how would you loop through an associative array via a foreach loop? – Rich Jenks Dec 18 '13 at 16:00
  • 5
    $associativeArray=@{ Jane=1 Tom=2 Harry=3 } foreach($key in $associativeArray.Keys) { $key } foreach($item in $associativeArray.GetEnumerator()) { "{0}={1}" -f $item.Key, $item.Value }×Comments must be at least 15 characters in length.×Comments must be at least 15 characters in length.×Comments must be at least 15 characters in length. – Doug Finke Dec 19 '13 at 14:34
  • `$associativeArray=@{ Jane=1 Tom=2 Harry=3 }` gives me `Unexpected token 'Tom=2' in expression or statement.` what works is `$associativeArray=@{ Jane=1; Tom=2; Harry=3 }` – stib May 27 '19 at 03:00
  • @stib, each value must either be on a seperate line (a simple return will do), or use a delimiter as you did. Seperate lines makes for easier readability. – Preben Brudvik Olsen Feb 04 '20 at 16:48
  • for anyone who wants a bit more dynamic keys: $Data = @{}; $Key = 'foo'; $Data.$Key = 'bar'; – Dxg125 Jan 20 '23 at 13:57
25

Yes. Use the following syntax to create them

$a = @{}
$a["foo"] = "bar"
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
21

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]
Ivan Temchenko
  • 814
  • 1
  • 9
  • 12
  • 2
    The only answer that mentions the semicolon `;` separator. – Géry Ogam Nov 09 '18 at 14:47
  • @Ivan Temchenko & @Maggyero, This is NOT A RELIABLE ANSWER, if you don't think so, then tell me why this code ```$shortcuts = @{'MyDocuments'='Personal';'MyComputer'='MyComputer'} Foreach($shortcut in $shortcuts.Keys) { Echo "\`$shortcut:$shortcut"; Echo "\`$shortcuts[\`$shortcut]:$shortcuts[$shortcut]" } Read-Host``` doesn't give me `MyDocuments` as key and `Personal` as it's value in the `$shortcuts` array ? (In the above code block, add newlines to make the code block work, it's just the limitation of comments that code blocks are not styled properly)... – Vicky Dev Sep 21 '22 at 22:19
  • @Viky Dev The problem is that within a string you should use $() for your expression: `"$($shortcuts[$shortcut])"` will give the expected result. In your example, Powershell is evaluating it as a Hashtable, a [, then a string, and another ]. When you enclose all of that in $() then it evaluates it as a powershell expression instead. I've just settled on always enclosing variables/expressions withing a string in $(). – Skrymsli Feb 03 '23 at 22:11
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
Joshua
  • 397
  • 1
  • 5
  • 7
2

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]
David Clarke
  • 12,888
  • 9
  • 86
  • 116
2
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()
js2010
  • 23,033
  • 6
  • 64
  • 66
2

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;
}
factorypolaris
  • 2,757
  • 12
  • 15
1

You can also do this:

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

Not associative array, but equally as useful.

-Oisin

x0n
  • 51,312
  • 7
  • 89
  • 111