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

gooly
  • 1,241
  • 7
  • 20
  • 38

2 Answers2

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

Dinesh Balasubramanian
  • 20,532
  • 7
  • 64
  • 57
Oscar Foley
  • 6,817
  • 8
  • 57
  • 90
  • ok - this works for "a" and "A" but now the keys 0..9 aren't accepted :( – gooly Jun 05 '14 at 07:47
  • I have tested code with keys 0..9 and works. I have edited answer to show that... – Oscar Foley Jun 05 '14 at 07:52
  • 2
    But this works: $hash.Add("0","..."); $hash.Add("a","..."); $hash.Add("A","..."); – gooly Jun 05 '14 at 07:56
  • if: $hash = New-Object system.collections.hashtable $hash.0 = "Check 0" I get: + $hash.0 <<<< = "Check 0" + CategoryInfo : ParserError: (.0:String) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : UnexpectedToken – gooly Jun 05 '14 at 08:00
  • Even accessing $hash.0 doesn't work, but $s="0";$hash.$s; gives me the value behind "0". – gooly Jun 05 '14 at 08:04
  • 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`) – Dinesh Balasubramanian Jan 04 '23 at 05:19
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"
Mohammad Nadeem
  • 9,134
  • 14
  • 56
  • 82