PowerShell Hash Tables Double Key Error: "a" and "A"
Asked Answered
R

2

10

from another application I have key-value pairs which I want to use in my script.
But there they have e.g. the keys "a" and "A" - which causes an Error double keys aren't allowed.

  $x = @{ "a" = "Entry for a"; "A" = "S.th.else for A" }

What can I do as I would need both or none?

Thanks in advance,
Gooly

Rickeyricki answered 5/6, 2014 at 7:26 Comment(0)
C
11

By default PowerShell Hash tables are case sensitive. Try this

$h = new-object System.Collections.Hashtable
$h['a'] = "Entry for a"
$h['A'] = "S.th.else for A"
$h[0] = "Entry for 0"
$h[1] = "Entry for 1"
$h

Output for $h: (it will treat a and A differently)

Name                           Value
----                           -----
A                              S.th.else for A
a                              Entry for a
1                              Entry for 1
0                              Entry for 0

Or this (depending on the syntax that you prefer)

$hash = New-Object system.collections.hashtable
$hash.a = "Entry for a"
$hash.A = "S.th.else for A"
$hash.0 = "Entry for 0"
$hash.1 = "Entry for 1"
$hash.KEY
$hash

But, if you create hashtable with @{} syntax. It is case insensitive

$x = @{}
$x['a'] = "Entry for a"
$x['A'] = "S.th.else for A"
$x[0] = "Entry for 0"
$x[1] = "Entry for 1"
$x

Output for $x: (it will treat a and A as same)

Name                           Value
----                           -----
a                              S.th.else for A
1                              Entry for 1
0                              Entry for 0

Note: Both $h.GetType() and $x.GetType() are of System.Object.Hashtable

Celluloid answered 5/6, 2014 at 7:32 Comment(6)
ok - this works for "a" and "A" but now the keys 0..9 aren't accepted :(Rickeyricki
I have tested code with keys 0..9 and works. I have edited answer to show that...Celluloid
But this works: $hash.Add("0","..."); $hash.Add("a","..."); $hash.Add("A","...");Rickeyricki
if: $hash = New-Object system.collections.hashtable $hash.0 = "Check 0" I get: + $hash.0 <<<< = "Check 0" + CategoryInfo : ParserError: (.0:String) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : UnexpectedTokenRickeyricki
Even accessing $hash.0 doesn't work, but $s="0";$hash.$s; gives me the value behind "0".Rickeyricki
Output of the above $h is having 4 keys (both a and A are present). Which means it is treating a and A differently. So it is case sensitive. Am i right ? @OscarFoley (If it right, we have to change the first line in your answer, by removing word not)Silicon
I
2

You can create a case-sensitive powerhsell hash table using System.Collections.Hashtable

$x = New-Object System.Collections.Hashtable 
$x['a']="Entry for a"
$x['A']="S.th.else for A"
Interlingua answered 5/6, 2014 at 7:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.