按周/月中每天的持续时间汇总任务?(POSH)

mbo*_*gon 3 powershell grouping pivot-table

我正在从Web服务解析JSON以获取我的任务(使用TimeFlip).现在,我收回每个任务,发生时间和持续时间,因此数据如下所示:

(taskname, start, durationinSec)
TaskA,"6/5/2018 12:16:36 PM",312
TaskB,"6/5/2018 12:30:36 PM",200
TaskA,"6/6/2018 08:00:00 AM",150
TaskA,"6/6/2018 03:00:00 PM",150
(etc etc)
Run Code Online (Sandbox Code Playgroud)

我想生成一个汇总报告,按天显示哪些任务有多少时间.

虽然数据将持续数周,但我只是想做一个每周报告,我可以轻松地将其转录到我们的时间应用程序中(因为他们不会给我一个API密钥).所以我会where {$_.start -gt (? {$_.start -gt (get-date -Hour 0 -Minute 00 -Second 00).adddays(-7)}先做点什么.

       6/5/2018    6/6/2018
 TaskA 312         300
 TaskB 200      
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?我假设group-object,但不清楚你如何做转轴甚至分组.

mkl*_*nt0 5

以下内容不输出数据透视表,但执行所需的分组和聚合:

$rows = @'
taskname,start,durationinSec
TaskA,"6/5/2018 12:16:36 PM",312
TaskB,"6/5/2018 12:30:36 PM",200
TaskA,"6/6/2018 08:00:00 AM",150
TaskA,"6/6/2018 03:00:00 PM",150
'@ | ConvertFrom-Csv

$rows | Group-Object { (-split $_.start)[0] }, taskname | ForEach-Object {
  $_ | Select-Object @{ n='Date'; e={$_.Values[0]} }, 
                     @{ n='Task'; e={$_.Values[1]} }, 
                     @{ n='Duration'; e={ ($_.Group | Measure-Object durationInSec -Sum).Sum } } 
}
Run Code Online (Sandbox Code Playgroud)

(-split $_.start)[0]start用空格分割每个值并返回第一个token([0]),它是时间戳的日期部分 ; 例如,6/5/2018返回6/5/2018 12:16:36 PM; 将此操作作为脚本块({ ... })传递,Group-Object意味着分组仅按日期发生,而不是时间(除分组之外taskname).

这会产生:

Date     Task  Duration
----     ----  --------
6/5/2018 TaskA      312
6/5/2018 TaskB      200
6/6/2018 TaskA      300
Run Code Online (Sandbox Code Playgroud)

要构建类似于pivot-table的输出需要更多的努力,并且它不会很快:

假设$objs包含上面创建的对象($objs = $rows | Group-Object ...).

# Get all distinct dates.
$dates = $objs | Select-Object -Unique -ExpandProperty Date
# Get all distinct tasks.
$tasks = $objs | Select-Object -Unique -ExpandProperty Task

# Create an ordered hashtable that contains an entry for each task that
# holds a nested hashtable with (empty-for-now) entries for all dates.
$ohtPivot = [ordered] @{}
$tasks | ForEach-Object {
  $ohtDates = [ordered] @{}
  $dates | ForEach-Object { $ohtDates[$_] = $null }
  $ohtPivot[$_] = $ohtDates
}

# Fill the hashtable from the grouped objects with the task- and 
# date-specific durations.
$objs | ForEach-Object { $ohtPivot[$_.Task][$_.Date] = $_.Duration }

# Output the resulting hashtable in pivot-table-like form by transforming
# each entry into a custom object
$ohtPivot.GetEnumerator() | ForEach-Object {
  [pscustomobject] @{ Task = $_.Key } | Add-Member -PassThru -NotePropertyMembers $_.Value
}
Run Code Online (Sandbox Code Playgroud)

以上产量:

Task  6/5/2018  6/6/2018
----  --------  --------
TaskA      312      300
TaskB      200         
Run Code Online (Sandbox Code Playgroud)

  • @TheIncorrigible1:在这种情况下,是的,但是`-split`的一元形式内置了额外的魔法:修剪前导空格和尾随空格,并通过任何非空的空格分割; 从本质上讲,它的分割方式与`awk`默认相同. (3认同)