Search code examples
powershellcsvgroup-object

Powershell - Group-Object Expand and Group again


I have a .csv file which I'm grouping on two properties 'DN', 'SKU' and then performing a sum on another property 'DeliQty' This works fine and the sum is reflected back to the group. However I then need to re group just on 'DN' and write out to separate files. I've tried Select-Object -Expand Group but this reverts to the original contents without the summed lines.

Is there a way to un group preserving the summed lines and then group again?

$CSVFiles = Get-ChildItem -Path C:\Scripts\INVENTORY\ASN\IMPORT\ -Filter *.csv

foreach ($csv in $CSVFiles) {
    $group = Import-Csv $csv.FullName | Group-Object DN, SKU
    $group | Where Count -gt 1 | ForEach-Object {
    $_.Group[0].'DeliQty' = ($_.Group | Measure-Object DeliQty -Sum).Sum 
    } 
    }

Solution

  • You may do the following:

    $CSVFiles = Get-ChildItem -Path C:\Scripts\INVENTORY\ASN\IMPORT\ -Filter *.csv
    
    foreach ($csv in $CSVFiles) {
        $group = Import-Csv $csv.FullName | Group-Object DN, SKU | Foreach-Object {
            if ($_.Count -gt 1) {
                $_.Group[0].DeliQty = ($_.Group | Measure-Object DeliQty -Sum).Sum
            }
            $_.Group[0]
        } 
        # outputs summed and single group objects
        $group
    }