Mezzan
Mezzan

Reputation: 329

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

Upvotes: 0

Views: 9744

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

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.

Upvotes: 6

Related Questions