Powershell Hashtable Count and Keys Properties getting overloaded

大城市里の小女人 提交于 2019-11-27 08:04:33

问题


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:

$hash = @{}
$hash.one = "Number 1"
$hash.two = "Number 2"

"Count is [{0}]" -f $hash.Count
$hash.Count = "Count's Hash Value"
"Count is now [{0}]" -f $hash.Count

My Output is this:

Count is [2]
Count is now [Count's Hash Value]

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:

$key = ":" + $key 

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.


回答1:


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

@{Count=123}.get_Count()
@{Count=123}|Select-Object -ExpandProperty Count # does not work on PowerShell Core

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

@{Count=123;PSBase=$null}.PSBase.Count
@{Count=123;PSObject=$null}.PSObject.Properties['Count'].Value


来源:https://stackoverflow.com/questions/35716939/powershell-hashtable-count-and-keys-properties-getting-overloaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!