Powershell从多行数组中计算总计

时间:2018-11-05 22:06:20

标签: powershell

我有一个包含以下数据的数组。我需要弄清楚如何合并数据并根据JobName进行报告。如果该工作仅具有成功状态,则总共为33;如果具有三个状态,则需要将所有工作名称加在一起。

JobName  Status  Count
Job #1   Success 33
Job #2   Failed  9
Job #2   Success 32
Job #2   Warning 5

这是我尝试过的一些代码。

$arrAllTasksBk = $taskListBk | Sort JobName | Select @{Name="JobName"; Expression = {$_.jobname}}, Status 
$arrAllTasksBk = $arrAllTasksBk | Group-object 'JobName', status |
 Select-Object @{n='JobName';e={$_.Group[0].'JobName'}}, @{n='Status';e={$_.Group[0].Status}}, Count

$arrAllTasksBk = $arrAllTasksBk | Sort JobName |  Select
            @{Name="JobName"; Expression = {$_.jobname}},
            @{Name="Total"; Expression = {$_.Count | Where {($_.status -match "Success") -or ($_.status -match "Warning")-or ($_.status -match "Failed")}}},
            @{Name="Failed"; Expression = {$_.Count | Where {$_.status -match"Failed"}}},
            @{Name="SuccessRate"; Expression = {$_.Count | Where {($_.status -match "Success") -or ($_.status -match "Warning")-or ($_.status -match "Failed")} / {$_.status -match "Success" }}}

1 个答案:

答案 0 :(得分:0)

这是获取这些数字的一种方法。删除或注释掉最终输出中不需要的项目... [咧嘴]

# fake reading in a CSV file
#    in real life, use Import-CSV
$InStuff = @'
JobName, Status, Count
Job #1, Success, 33
Job #2, Failed,  9
Job #2, Success, 32
Job #2, Warning, 5
'@ | ConvertFrom-Csv

$GroupedInStuff = $InStuff |
    Group-Object -Property JobName

$Results = foreach ($GIS_Item in $GroupedInStuff)
    {
    $Success = [int]($GIS_Item.Group.Where({$_.Status -eq 'Success'}))[0].Count
    $Failed = [int]($GIS_Item.Group.Where({$_.Status -eq 'Failed'}))[0].Count
    $Warning = [int]($GIS_Item.Group.Where({$_.Status -eq 'Warning'}))[0].Count
    $Total = $Success + $Failed + $Warning
    [PSCustomObject]@{
        JobName = $GIS_Item.Name
        TotalCount = $Total
        Success = $Success
        Failed = $Failed
        # to remove the "Warning" items, comment out the next line
        Warning = $Warning
        # to get an int percent [70 instead of 69.57]
        #    use the following line
        # SuccessPct = [int]('{0:N0}' -f ($Success / $Total * 100))
        SuccessPct = [decimal]('{0:N2}' -f ($Success / $Total * 100))
        }
    }

$Results

输出...

JobName    : Job #1
TotalCount : 33
Success    : 33
Failed     : 0
Warning    : 0
SuccessPct : 100.00

JobName    : Job #2
TotalCount : 46
Success    : 32
Failed     : 9
Warning    : 5
SuccessPct : 69.57