简体   繁体   中英

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 
    } 
    }

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM