【问题标题】:How do I retrieve a HashTable key from a value?如何从值中检索 HashTable 键?
【发布时间】:2015-07-26 17:20:58
【问题描述】:

我有一个 PowerShell HashTable,其中包含一组键值对(自然而然)。所有的 HashTable 值都是唯一的。

我想使用 PowerShell 根据我指定的值检索 HashTable 键。

【问题讨论】:

  • duplicate 但在这个问题下,@Vadim 提供了唯一干净而全面的答案

标签: powershell


【解决方案1】:

您可以使用 PowerShell 4.0 的 Where 方法语法来实现这一点。 Where 方法接受 PowerShell ScriptBlock 来查找符合指定条件的对象。我们可以遍历 HashTable 键并找到包含所需值的键。

如果您确实有重复 HashTable 的情况,您可以选择指定第二个参数,类型为 WhereOperatorSelectionMode,指定调用应返回的对象哪里方法。通过为第二个方法参数指定First,我们可以确保只返回一个HashTable key。

第二个参数支持的所有值如下:

  • 默认
  • 首先
  • 最后
  • SkipUntil
  • 直到
  • 拆分

$HashTable = @{
    1 = 10;
    2 = 20;
    3 = 30;
}

$Val = 30;
$HashTable.Keys.Where({ $HashTable[$PSItem] -eq $Val; }, [System.Management.Automation.WhereOperatorSelectionMode]::First);

【讨论】:

    【解决方案2】:

    其他选项:

    • 遍历 HashTable 键并找到包含 价值:
      $HashTable.Keys |? { $HashTable[$_] -eq $Val }
    • 使用GetEnumerator()函数进行迭代:

      $HashTable.GetEnumerator() | ?{ $_.Value -eq $Val } | %{ $_.Key }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      • 1970-01-01
      • 2020-09-19
      • 1970-01-01
      • 2022-01-06
      • 2020-02-20
      • 2011-01-14
      相关资源
      最近更新 更多