Grouping collection of objects by different conditions

I have a group of objects in a collection. Example:

Date Particulars Amount
10/10/2017 Expense 1 $55.00
11/10/2017 Expense 2 $100.00
11/11/2017 Expense 3 $160.00

What I would like is to have the collection grouped by month. …I did this as date/month/year. So there will be 2 entry in october
and 1 entry in November…

It should end up something like this like this:

10/10/2017 Expense 1 $55.00
11/10/2017 Expense 2 $100.00

11/11/2017 Expense 3 $160.00

I know i can group it in format-table and use groupby…but grouping them in a custom manner like this…i am a lost as to how it could be done…Any help please would be appreciated.

So you want to group them by month and print them the same way as you show? Simplest way to do that is to group by Month. Output the month, and then output the whole group.

I am doing something similar with my commit history, but I group per day:

$myCommits | 
    sort date | 
    group date | 
    foreach { 
        $_.Group | foreach { 
            $_.project + " " +$_.commit + " " + $_.message 
pester_main ae07a35 forward merge master
pester_main 6410254 remove progress to make execution faster and fix linux formatting errors

pester_main 0e6b1c9 Add more badges

pester_main fda3bfd Bump to 4.1.0

Group-Object can take a scriptblock to allow custom grouping, so something like this might work:

# Numeric month:
$data | Group-Object { ($_.Date -as [datetime]).Month }

# Short date string:
$data | Group-Object { ($_.Date -as [datetime]).ToString('MMM') }

# Full date string:
$data | Group-Object { ($_.Date -as [datetime]).ToString('MMMM') }

If you want to use Format-Table, it can take custom properties like Select-Object does, so maybe something like this:

$data | sort Date | Format-Table -GroupBy @{Label='Month'; Expression={ ($_.Date -as [datetime]).ToString('MMM')}}

That won’t give you the exact output you have, but nohandle’s answer shows how you an fix that :slight_smile: