0

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
4
  • 2
    Can you show your desired output for this? Your array list just contains strings. Group object has no metrics with which to coordinate this. Sounds like you want a collection of site and item objects instead. Commented Aug 20, 2018 at 12:21
  • @Matt added desired output example. Collection of site and item objects? Googling it now. Commented Aug 20, 2018 at 12:45
  • Site A | Item A | 3 should be 2 correct? Commented Aug 20, 2018 at 12:49
  • Ah yes. Edited. My bad. Commented Aug 20, 2018 at 12:51

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

removing property 'Value' gives me the result so much closer to what i needed. Incredible!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.