jea*_*nat 4 powershell dictionary enumeration hashtable
所以,我对 PowerShell 相当陌生,只是不知道如何使用数组/列表/哈希表。我基本上想做Python描述的以下事情:
entries = {
'one' : {
'id': '1',
'text': 'ok'
},
'two' : {
'id': '2',
'text': 'no'
}
}
for entry in entries:
print(entries[entry]['id'])
Run Code Online (Sandbox Code Playgroud)
输出:
1
2
但这在 PowerShell 中是如何工作的呢?我尝试过以下方法:
$entries = @{
one = @{
id = "1";
text = "ok"
};
two = @{
id = "2";
text = "no"
}
}
Run Code Online (Sandbox Code Playgroud)
现在我不知道如何访问这些信息。
foreach ($entry in $entries) {
Write-Host $entries[$entry]['id']
}
Run Code Online (Sandbox Code Playgroud)
=> 错误
PowerShell 防止对字典进行隐式迭代,以避免意外“展开”。
您可以解决这个问题,并通过显式调用循环遍历包含的键值对GetEnumerator()
:
foreach($kvp in $entries.GetEnumerator()){
Write-Host $kvp.Value['id']
}
Run Code Online (Sandbox Code Playgroud)
对于更接近 python 示例的内容,您还可以提取键值并迭代这些值:
foreach($key in $entries.get_Keys()){
Write-Host $entries[$key]['id']
}
Run Code Online (Sandbox Code Playgroud)
注意:您会发现迭代$entries.Keys
也有效,但我强烈建议不要使用它,因为 PowerShell 通过属性访问解析字典键,因此如果字典包含带有 key 的条目,您将得到意外的行为"Keys"
:
$entries = @{
Keys = 'a','b'
a = 'discoverable'
b = 'also discoverable'
c = 'you will never find me'
}
foreach($key in $entries.Keys){ # suddenly resolves to just `'a', 'b'`
Write-Host $entries[$key]
}
Run Code Online (Sandbox Code Playgroud)
您只会看到输出:
discoverable
also discoverable
Run Code Online (Sandbox Code Playgroud)
不是Keys
或c
条目