Home > Mobile >  Powershell - Group and count from CSV file
Powershell - Group and count from CSV file

Time:03-10

In my CSV file, I have two columns with header Start_date and Status. I am trying to find out the success percentage for each Start_date

    Start_date       Status
------------------------------------------
    02-03-2022      Completed
    02-03-2022      Completed
    03-03-2022      Failed
    03-03-2022      Completed

I am looking for a final output like below which I export CSV

Start_date  Total Completed  Failed Success %
02-03-2022   2       2         0      100
03-03-2022   2       1         1       50

As a first step, I am trying to get the count of each day job using below code.

$data = Import-Csv "C:\file.csv"
$data | group {$_.Start_date} | Sort-Object {$_.Start_date} | Select-Object {$_.Status}, Count

Above code will give me output like

$_.Status Count
--------- -----
              1
              1

it is not showing the date value. what will be the correct approach for this issue ?

CodePudding user response:

You can use Group-Object to group the objects by the date column, then it's just math:

$csv = @'
Start_date,Status
02-03-2022,Completed
02-03-2022,Completed
03-03-2022,Failed
03-03-2022,Completed
'@ | ConvertFrom-Csv

# This from your side should be:
# Import-Csv path/to/csv.csv | Group-Object ....

$csv | Group-Object Start_date | ForEach-Object {
    $completed, $failed = $_.Group.Status.where({ $_ -eq 'Completed' }, 'Split')
    $totalc  = $_.Group.Count
    $complc  = $completed.Count
    $failc   = $failed.Count
    $success = $complc / $totalc

    [pscustomobject]@{
        Start_Date = $_.Name
        Total      = $totalc
        Completed  = $complc
        Failed     = $failc
        Success    = $success.ToString('P0')
    }
}

CodePudding user response:

Here's another one:

$csv = Import-Csv C:\Temp\tmp.csv
$Results = @()
foreach ($group in $csv | Group Start_date)
{
    $Completed = ($group.Group | group status | ? Name -eq Completed).Count
    $Failed = ($group.Group | group status | ? Name -eq Failed).Count
    $row = "" | Select Start_date,Total,Completed,Failed,"Success %"
    $row.Start_date = $group.Name 
    $row.Total = $group.Count
    $row.Completed = $Completed
    $row.Failed = $Failed
    $row."Success %" = $Completed / 2 * 100
    $Results  = $row
}

$results

Start_date Total Completed Failed Success %
---------- ----- --------- ------ ---------
02-03-2022     2         2      0       100
03-03-2022     2         1      1        50
  • Related