Search code examples
powershellhashtable

PowerShell Hash Tables Double Key Error: "a" and "A"


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


Solution

  • 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