Powershell: counting unique strings via hash table

hashtable, powershell, unique

Solution

Your approach looks quite good, at least for PowerShell with its helpers for hashtables. Just keep in mind that hashtables defined as `@{}` are case insensitive. If you need a case sensitive hashtable then create it like `New-Object System.Collections.Hashtable`.

Example:

# case insensitive
$hash = @{}
$hash['a']++
$hash['A']++
$hash

'------------------------'

# case sensitive
$hash = New-Object System.Collections.Hashtable
$hash['a']++
$hash['A']++
$hash

Output:

Name                           Value
----                           -----
a                              2
------------------------
a                              1
A                              1

In C# using `Dictionary<string, int>` is probably a "better practice". It is also possible in PowerShell but it unlikely makes things much "better" in PowerShell.

A PowerShell-ish solution is probably use of `Group-Object -NoElement`. Is it a better approach or practice? I do not know. It depends on a few factors including preferences. Here is the example:

'a', 'A', 'foo', 'foo' , 'bar' | Group-Object -NoElement

Output:

Count Name
----- ----
    2 a
    2 foo
    1 bar

Problem

An "it works -- but is it a best practice?" question. In Perl there's a compact way of keeping track of occurrences of, say, strings found within a file: store them in a hash table. For example: ``` $HashTable{'the string in question'}++; ``` Perl increments the value for key `the string in question` as many times as this is done. It ensures unique "hits" at the same time that it keeps track of occurrences. Just hacking around, I found I could do much the same with Powershell: `$HashTable['a']++` or even `$Hashtable.a++` (which kind of surprised me -- or even) `$Hashtable."this is a key"++` Ok, so it works. But is there an approach in Powershell that's considered a better practice?

Original source