我在PowerShell中使用哈希表,我注意到一些与访问项目有关的奇怪行为.我们知道,PowerShell至少允许三种不同的方式为散列表条目赋值:
$hashtable["foo"] = "bar" #1
$hashtable.Item("foo") = "bar" #2
$hashtable.foo = "bar" #3
Run Code Online (Sandbox Code Playgroud)
同时,我们使用#3语法访问Hashtable对象本身,如性能Count,Keys,Values等如果我们有与内部属性的名称冲突的关键添加项目,PowerShell的让我们这样做,我们实际上不再能够读取属性的值(除了使用Reflection).
我想在密钥来自不可信赖的来源(例如来自外部文件或网络)的情况下,这可能会对流量控制产生不良影响,并且可能被恶意用户利用.
此代码段演示了此问题:
function Get-HashtableProperties($hashTable, $header)
{
"{0} {1} {0}" -f ("-" * 10), $header
"Count : {0}" -f $hashtable.Count
"Keys.Count : {0}" -f $hashtable.Keys.Count
"Values.Count : {0}" -f $hashtable.Values.Count
"Actual Count (Reflection) : {0}" -f $hashtable.GetType().GetProperty("Count").GetValue($hashtable)
"`nItems (Keys iteration):"
$hashtable.Keys | ForEach-Object { " [ {0} = {1} ]" -f $_, $hashtable.Item($_) }
"`nItems (Enumerator iteration):"
$enumerator = $hashTable.GetEnumerator()
while …Run Code Online (Sandbox Code Playgroud)