Group By Day in PowerShell

Ok I have this script where I read in CSV (converted from XLS) and saved the ID field as well as the date field into an array. For instance:

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 number of items in each day, without having to scroll foreach, etc. Is there a better solution for this? (Note that it TheDatecontains different times that I would like to ignore.)

+3
source share
2 answers

Group-Objectallows you to use script blocks as values -Property. So you can use the property Dateto group:

# 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}
+5

, :

$startDate = [DateTime]::Parse($startDate)
$endDate = [DateTime]::Parse($endDate)

$items = $items | Where { $_.TheDate -gt $startDate -and $_.TheDate -lt $endDate } | Sort-Object -Property TheDate

$dates = @{}

foreach ($item in $items)
{
    $dates.($item.TheDate.ToShortDateString()) += 1
}
+1

Source: https://habr.com/ru/post/1770258/


All Articles