Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

csv - 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:ScriptsINVENTORYASNIMPORT -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 
    } 
    }
question from:https://stackoverflow.com/questions/65925745/powershell-group-object-expand-and-group-again

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You may do the following:

$CSVFiles = Get-ChildItem -Path C:ScriptsINVENTORYASNIMPORT -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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...