By default hash tables created by PowerShell (e.g. $hashtable = @{}
) are case insensitive.
For my script I want to explicitly create a case sensitive hash table.
This can be done by:
$hashtable = [hashtable]::new()
or:
$hashtable = New-Object hashtable
But I want to have my script also compliant with the default PSScriptAnalyzer rules. For the above case sensitive hash table examples, the UseLiteralInitializerForHashtable rule cases a warning:
Use literal initializer, @{{}}, for creating a hashtable as they are case-insensitive by default
I would expect to be able to work arround this by specifying the StringComparer
, like:
[HashTable]::New(0, [StringComparer]::Ordinal)
But this still generates an error (although [HashTable]::New(0, [StringComparer]::OrdinalIgnoreCase)
doesn't).
AFAIK, there is not something like: [StringComparer]::OrdinalMatchCase
, or?
How to create a case sensitive Hashtable without generating a PSScriptAnalyzer warning?
PSScriptAnalyzer version: 1.18.3
Tested both Windows PowerShell (5.1
) and PowerShell Core (6.2.3
)
Steps to reproduce the warning:
Invoke-ScriptAnalyzer -ScriptDefinition '[HashTable]::New(0, [StringComparer]::Ordinal)'