Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Group by day" in PowerShell

Ok I have this script where I read in a CSV (converted from a XLS) and save an ID-field as well as a date-field into an array. Like so:

New-Object PSObject -prop @{
    TheId = $_."The ID";
    TheDate = [DateTime]::Parse($_."The Date")
}

It works like a charm and I get a nice array of objects with the two properties above. Now, I would like to get the count of items on each day, without having to do a foreach to loop through and such. Is there a nicer solution to it? (Note that TheDate contains different times too, which I'd like to ignore.)

like image 475
Robin Avatar asked Mar 24 '26 07:03

Robin


1 Answers

Group-Object allows to use script blocks as -Property values. So that you can use Date property for grouping:

# demo: group temporary files by modification date (day!):
Get-ChildItem $env:temp | Group-Object {$_.LastWriteTime.Date}

# answer for your example:
$objects | Group-Object {$_.TheDate.Date}
like image 176
Roman Kuzmin Avatar answered Mar 26 '26 03:03

Roman Kuzmin