Powershell Hashtable Count and Keys Properties getting overloaded

Question:

Problem Statement: The Count and Keys properties can get overloaded by a hash value and not return their expected values.

My Powershell Code is this:

My Output is this:

The Count Property gets overloaded! This issues could cause users some very hard to diagnose bugs. Had me confused for a good while. Same issue applies to “Keys” or in fact any Property.

Do you have any thoughts on best practice to avoid this one? Maybe a different System.Collection? or prefixing all Keys with a character such as:

However, its not very elegant. Even now that I know the issue, I suspect I will forget and make the same mistake again.

I personally think it is a problem with the Powershell Language Definition. The . notation (as in $hash.MyKey) should not be allowed for retrieving hash values, only for retrieving Property values. Just a thought. 🙂

Thanks for your help.

Answer:

You can directly call property get accessor instead of accessing property or use Select-Object -ExpandProperty:


In PowerShell v3+ you could also use PSBase or PSObject automatic property:

Source:

Powershell Hashtable Count and Keys Properties getting overloaded by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply