Thursday, September 1, 2016

PowerShell Case Insensitive Hashtable Key Search

Had an issue today where a specific Azure resource tag was not being written per my specification.  For instance, I was writing the tag as "BornOn", but the actual resource would show "bornOn" or "Bornon" or some other combination.  Very strange issue on the Azure API side, that is for sure.  When I would come back around to check the resource for the existence of the BornOn tag, in some cases it was not found.  A bit perplexing at first!

I was using the following format to check:

$oResource.Tags -contains "BornOn"

This particular method IS case sensitive!  So are a lot of the other methods such as Contains, ContainsKey, etc. for hash table searching.  This was my workaround:

$oResource.Tags.GetEnumerator() | Where-Object { $_.Name -eq 'BornOn'}

This will catch all the various case types of the word 'BornOn'.  Wrap this in an if statement to see if the key was found or not.

No comments:

Post a Comment