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

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...