我有以下对象结构:
所以我可以做$resources[0].Tags.Owner并获取字符串值。
目标只是select名称和所有者,然后group是所有者。
我可以这样做$resources | select {$_.Tags.Owner, $_.Name},但随后我得到了一个新的 PSCustomObject 数组,其中包含两个成员“$ .Tags.Owner”和“$ .Name”。如何按名为“$_.Tags.Owner”的字段进行分组?
group我的意思是“$_.Tags.Owner”字面意义而不是对象层次结构吗?解决方案:
#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- 在具有相同所有者属性值的组中。| 归档时间: |
|
| 查看次数: |
3595 次 |
| 最近记录: |