首页 > 解决方案 > 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" }}}

标签: powershell

解决方案


这是获得这些数字的一种方法。在最终输出中删除或注释掉您不想要的项目... []

# 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

推荐阅读