简体   繁体   中英

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 . 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.

In PowerShell v3 and newer you can simplify that to

$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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM