Lazy Diary @ Hatena Blog

PowerShell / Java / miscellaneous things about software development, Tips & Gochas. CC BY-SA 4.0/Apache License 2.0

Avoid error when adding duplicated keys to hash (case sensitivity in hash tables on PowerShell)


Keys of hash tables are case sensitive in most languages (Java/JavaScript/Perl/Ruby/…). But in PowerShell, key of hash table is case insensitive (if you use string as key), so you will bump into errors in code like:

PS > $hash = @{}; (0x7E..0x21 | ForEach-Object { $hash.Add("{0}" -F [char]$_, $_) })
Exception calling "Add" with "2" argument(s): "Item has already been added. Key in dictionary: 'z'
 Key being added: 'Z'"
At line:1 char:45
+ ... }; (0x7E..0x21 | ForEach-Object { $hash.Add("{0}" -F [char]$_, $_) })
+                                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentException


It seems by design.


Dedupe keys with Sort-Object -Unique (case insensitive dedupe) before put keys to hash table.