在PowerShell中从键(嵌套字典中)获取值

z9smfwbn  于 2023-06-23  发布在  Shell
关注(0)|答案(1)|浏览(204)

我的示例字典

$testHashMap = @{
    'feature1' = @{
        'Audit'@{
          'color' = "white"
          'price' = 3
        }
        'Space'  = 2
        'Usage' = 3
    }
    'feature2' = @{
        'Audit'@{
          'color' = "black"
          'price' = 3
        }
        'Space'  = 5
        'Usage' = 3
    }
}
  • 如何直接访问“颜色”键的值?
  • 当我提示一个键时,它将搜索相关的键并返回其值

预期输出:

Please enter a property: "color"
Color: white in feature1
Color: black in feature2

我想用递归来做,我怎样才能达到这个目的呢?

cxfofazt

cxfofazt1#

来自this answer的自定义Get-LeafProperty函数可以处理任意对象图作为输入,包括嵌套的hashtables(字典),如您的问题所示。
它将叶属性/字典条目报告为名称-路径/值对;例如,对于您的第一个color条目,它返回以下custom object(在这里表示为文字):
[pscustomobject] @{ NamePath = 'feature1.Audit.color'; Value = 'white' }
因此,您可以将此函数与Where-ObjectForEach-Object组合使用,以通过感兴趣的叶键过滤输出:

$keyName = 'color'

# The key of the leaf entries of interest.
$keyName = 'color'

@{  # sample input hashtable from you question; streamlined and syntax-corrected
  feature1 = @{
    Audit = @{
      color = 'white'
      price = 3
    }
    Space = 2
    Usage = 3
  }
  feature2 = @{
    Audit = @{
      color = 'black'
      price = 3
    }
    Space = 5
    Usage = 3
  }
} | 
  Get-LeafProperty | 
  Where-Object { ($_.NamePath -split '\.')[-1] -eq $keyName } |
  ForEach-Object {
    "${keyName}: $($_.Value) in $(($_.NamePath -split '\.')[0])"
  }

输出:

color: white in feature1
color: black in feature2

相关问题