【发布时间】:2015-07-26 17:20:58
【问题描述】:
我有一个 PowerShell HashTable,其中包含一组键值对(自然而然)。所有的 HashTable 值都是唯一的。
我想使用 PowerShell 根据我指定的值检索 HashTable 键。
【问题讨论】:
-
duplicate 但在这个问题下,@Vadim 提供了唯一干净而全面的答案
标签: powershell
我有一个 PowerShell HashTable,其中包含一组键值对(自然而然)。所有的 HashTable 值都是唯一的。
我想使用 PowerShell 根据我指定的值检索 HashTable 键。
【问题讨论】:
标签: powershell
您可以使用 PowerShell 4.0 的 Where 方法语法来实现这一点。 Where 方法接受 PowerShell ScriptBlock 来查找符合指定条件的对象。我们可以遍历 HashTable 键并找到包含所需值的键。
如果您确实有重复 HashTable 值 的情况,您可以选择指定第二个参数,类型为 WhereOperatorSelectionMode,指定调用应返回的对象哪里方法。通过为第二个方法参数指定First,我们可以确保只返回一个HashTable key。
第二个参数支持的所有值如下:
$HashTable = @{
1 = 10;
2 = 20;
3 = 30;
}
$Val = 30;
$HashTable.Keys.Where({ $HashTable[$PSItem] -eq $Val; }, [System.Management.Automation.WhereOperatorSelectionMode]::First);
【讨论】:
其他选项:
$HashTable.Keys |? { $HashTable[$_] -eq $Val }
使用GetEnumerator()函数进行迭代:
$HashTable.GetEnumerator() | ?{ $_.Value -eq $Val } | %{ $_.Key }
【讨论】: