开发者

"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 i开发者_C百科tems 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.)


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}


I solved it with a loop, at least for now:

$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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜