【问题标题】:Looking for a Powershell way to group multiple dates by week寻找一种按周对多个日期进行分组的 Powershell 方法
【发布时间】:2022-10-03 09:58:09
【问题描述】:

我有一个 CSV 交易文件。我一直在寻找一种方法来对每周的交易进行分组。

我知道 PowerShell 有 Group-Object 这可以将所有内容分组到单独的日期中,我希望按周汇总。

提前致谢!

我正在查看Transaction Date 并希望遍历所有行以将事物分组到“7 天”存储桶中。例如,从 8/31 到 8/24,然后是 8/24 到 8/17,依此类推。

CSV 样本:

Transaction Date,Posted Date,Card No.,Description,Category,Debit
8/31/2022,9/1/2022,1,Meals on wheels!,a,3.5
8/30/2022,9/1/2022,1,Meals on wheels!,b,3.5
8/30/2022,8/31/2022,1,Meals on wheels!,c,3.5
8/30/2022,8/31/2022,1,Meals on wheels!,a,3.5
8/29/2022,8/31/2022,1,Meals on wheels!,a,3.5
8/29/2022,8/30/2022,1,Meals on wheels!,a,3.5
8/26/2022,8/29/2022,1,Meals on wheels!,b,3.5
8/28/2022,8/29/2022,1,Meals on wheels!,b,3.5
8/27/2022,8/29/2022,1,Meals on wheels!,b,3.5
8/25/2022,8/26/2022,1,Meals on wheels!,b,3.5
8/25/2022,8/26/2022,1,Meals on wheels!,b,3.5
8/23/2022,8/24/2022,1,Meals on wheels!,c,3.5
8/23/2022,8/24/2022,1,Meals on wheels!,c,3.5
8/22/2022,8/23/2022,1,Meals on wheels!,c,3.5
8/21/2022,8/23/2022,1,Meals on wheels!,c,3.5
8/21/2022,8/23/2022,1,Meals on wheels!,a,3.5
8/21/2022,8/22/2022,1,Meals on wheels!,a,3.5

添加一些看起来很接近但我不确定逻辑的东西,因为 CSV 中的日期是按降序排列的,所以AddDays(-7) 似乎是朝着正确方向迈出的一步。

$NextWeekNeeded = $true

$csv | ForEach-Object {

[datetime]$CurrentDay = $PSItem.\'Transaction Date\'

    IF($NextWeekNeeded){

    write-host -ForegroundColor Cyan \'Next week needed\'

    $Week = $CurrentDay.AddDays(-7)

    $WeekInfo = \"Week: {0}\" -f $Week

    Write-Host -ForegroundColor Yellow $WeekInfo

    $NextWeekNeeded = $false

    #$PSItem

    }

    IF($CurrentDay -ge $Week){

    $PSItem | select \'Transaction Date\', Description, Debit

    } Else {

    $NextWeekNeeded = $true

    }

}

}
  • 你能发布一个经过消毒的 csv,前后有什么预期的结果吗?
  • @AbrahamZinala 当然,我完全忽略了发布示例 CSV。

标签: powershell date


【解决方案1】:

同上什么'亚伯拉罕齐纳拉',说没有它集中我们去猜测。

尽管如此,你的意思是这样的:

Clear-Host
 @(
'01/01/2022',
'01/01/2022',
'01/02/2022',
'01/03/2022',
'01/03/2022',
'01/03/2022'
) | 
ForEach-Object {((Get-Date($PSItem)).AddDays(7))} | 
Group-Object | 
Select-Object -Property Count, Name

# Results
<#
Count Name              
----- ----              
    2 08-Jan-22 00:00:00
    1 08-Feb-22 00:00:00
    3 08-Mar-22 00:00:00
#>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-04
    • 2020-10-07
    • 2016-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多