【问题标题】:PowerShell select and group by nested fieldPowerShell 按嵌套字段选择和分组
【发布时间】:2016-10-13 21:39:17
【问题描述】:

我有以下对象结构:

  • 资源(数组)
    • 资源 (PSCustomObject)
      • 名称(字符串)
      • 标签 (PSCustomObject)
        • 所有者(字符串)
      • 更多...

所以我可以做$resources[0].Tags.Owner 并获取字符串值。

目标是 select 只是名称和所有者,然后是 group 所有者。

我可以$resources | select {$_.Tags.Owner, $_.Name},但随后我得到了一个新的 PSCustomObject 数组,其中包含两个成员“$.Tags.Owner”和“$.Name”。 如何按名为“$_.Tags.Owner”的字段进行分组?

  1. 我可以将“$_.Tags.Owner”重命名为更友好的名称和所属的组吗?
  2. 我能否以某种方式告诉group,我的意思是“$_.Tags.Owner”,而不是对象层次结构?

【问题讨论】:

    标签: powershell


    【解决方案1】:

    解决方案:

    #Demo Data Setup
    Clear-Host
    [PSCustomObject[]]$resources = @(
        [PSCustomObject]@{Name='One';Tags=[PSCustomObject]@{Owner='Anne'}}
        [PSCustomObject]@{Name='Two';Tags=[PSCustomObject]@{Owner='Bob'}}
        [PSCustomObject]@{Name='Three';Tags=[PSCustomObject]@{Owner='Claire'}}
        [PSCustomObject]@{Name='Four';Tags=[PSCustomObject]@{Owner='Anne'}}
        [PSCustomObject]@{Name='Five';Tags=[PSCustomObject]@{Owner='Bob'}}
    )
    
    
    #Solution
    $resources | Select-Object Name, @{Name='Owner';Expression={$_.Tags.Owner}} | Group-Object -Property Owner
    
    #Or a more verbose option which may be better in other scenarios
    $resources | ForEach-Object {
        $Name = $_.Name
        $_.Tags | Select-Object Owner, @{Name='Name';Expression={$Name}} 
    } | Group-Object -Property Owner
    

    解释:

    • $resources - 将资源数组传递到管道中
    • Select-Object - 对于每个资源,返回从该资源派生的属性集合
    • Name - 取 name 属性
    • @{Name='Owner';Expression={$_.Tags.Owner}} - 创建一个名为 Owner 的新属性,其值为当前资源标签的属性所有者。
    • Group-Object - 将管道中的所有属性组合在一起
    • -Property Owner - 在拥有相同 Owner 属性值的组中。

    【讨论】:

    • 谢谢。我之前尝试过使用 Name\Expression 进行选择,但我遇到了语法错误。现在工作。谢谢
    猜你喜欢
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多