PowerShell 按嵌套字段选择和分组

ita*_*ysk 4 powershell

我有以下对象结构:

  • 资源(数组)
    • 资源(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”字面意义而不是对象层次结构吗?

Joh*_*van 6

解决方案:

#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
# (thanks to zumalifeguard in the comments for pointing out this optimisation)
$resources | Group-Object -Property { $_.Tags.Owner }

#Original 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
Run Code Online (Sandbox Code Playgroud)

解释:

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