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?
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 likeNew-Object System.Collections.Hashtable.Example:
Output:
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:Output: