[英]Powershell Group-object array list
Two comma separated item added in array list and I would like to group them to count the total. 数组列表中添加了两个逗号分隔的项目,我想将它们分组以计算总数。
$list_distinct = [System.Collections.ArrayList]@()
$list_distinct.Add("Site A,Item A")
$list_distinct.Add("Site A,Item A")
$list_distinct.Add("Site A,Item B")
$list_distinct.Add("Site B,Item C")
$list_distinct.Add("Site B,Item D")
$list_distinct.Add("Site B,Item D")
Tried this: 试过这个:
$test = $list_distinct | Group-Object Values
The result shows Count (the whole total), Name(empty) and Group (the whole added items). 结果显示计数(总数),名称(空)和组(全部添加的项目)。
Any way to fix this? 有任何解决这个问题的方法吗? Or is there any better method?
还是有更好的方法?
Desired output example: 所需的输出示例:
Site | Item | Count
Site A | Item A | 2
Site A | Item B | 1
Site B | Item C | 1
Site B | Item D | 2
Neither the ArrayList
object nor its elements have a property Values
. ArrayList
对象及其元素都不具有Values
属性。 Non-existent properties are expanded to an empty result, so all of your values are grouped under the same (empty) name. 不存在的属性将扩展为空结果,因此所有值都分组在相同(空)名称下。
Change this 改变这个
$list_distinct | Group-Object Values
into this 进入这个
$list_distinct | Group-Object
and the problem will disappear. 问题就会消失。
For your desired output you will also need to split the values and create new (custom) objects: 对于所需的输出,您还需要拆分值并创建新的(自定义)对象:
$list_distinct | Group-Object | ForEach-Object {
$site, $item = $_.Name -split ','
New-Object -Type PSObject -Property @{
'Site' = $site
'Item' = $item
'Count' = $_.Count
}
} | Select-Object Site, Item, Count
The trailing Select-Object
is to enforce field order since PowerShell hashtables aren't ordered by default. 尾随的
Select-Object
将强制执行字段顺序,因为默认情况下未对PowerShell哈希表进行排序。
In PowerShell v3 and newer you can simplify that to 在PowerShell v3和更高版本中,您可以简化为
$list_distinct | Group-Object | ForEach-Object {
$site, $item = $_.Name -split ','
[PSCustomObject]@{
'Site' = $site
'Item' = $item
'Count' = $_.Count
}
}
The trailing Select-Object
isn't needed here, because the [PSCustomObject]
type accelerator implicitly uses an ordered hashtable. 这里不需要尾随的
Select-Object
,因为[PSCustomObject]
类型加速器隐式使用有序哈希表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.