6

Referencing Non-String Hashtable Keys in PowerShell

 3 years ago
source link: https://thomasrayner.ca/referencing-non-string-hashtable-keys-in-powershell/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Referencing Non-String Hashtable Keys in PowerShell

Say you’ve got a hashtable with a bunch of data in it, but the key is not a string. How do you refer to specific items?

You can set something up to experiment with this with this code.

PS> $a = @{}
PS> 1..3 | % { $a.add($(New-Guid), $_) }

Declare $a as a new empty hashtable, and then add three items to it. The key is a GUID, and the value is just a number. You get something like this.

PS> $a

Name                           Value
----                           -----
a2022422-ffe6-4291-a736-c1d... 1
33b8251c-8c09-433c-ae88-666... 3
4d9d41c1-8a0b-4326-ad59-164... 2

Now say you want to refer to the first item in the list whose key/GUID is a2022422-ffe6-4291-a736-c1de97720f25, in my example. You could try any of these.

PS> $a.a2022422-ffe6-4291-a736-c1de97720f25
PS> $a.'a2022422-ffe6-4291-a736-c1de97720f25'
PS> $a['a2022422-ffe6-4291-a736-c1de97720f25']
PS> $a.Item('a2022422-ffe6-4291-a736-c1de97720f25')

But none of these actually return any information. The problem is that the key is a GUID, not a string, but we’re trying to refer to it as a string. Instead, you have to treat it like a GUID.

PS> $a[[guid]'a2022422-ffe6-4291-a736-c1de97720f25']

1

By casting the string as a GUID, you’re telling the hashtable that you’re not just looking for a string. This same thing works for other data types like integers.

Written on November 15, 2017

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK