Author Posts

November 15, 2017 at 5:08 pm

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:

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

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

November 15, 2017 at 7:57 pm

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 { 
        "`n"+$_.Name
        $_.Group | foreach { 
            $_.project + " " +$_.commit + " " + $_.message 
        }
    }
2017-11-12
pester_main ae07a35 forward merge master
pester_main 6410254 remove progress to make execution faster and fix linux formatting errors

2017-11-14
pester_main 0e6b1c9 Add more badges

2017-11-15
pester_main fda3bfd Bump to 4.1.0

November 15, 2017 at 8:12 pm

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 🙂