GP中的Powershell Group对象并将其导出

时间:2015-02-27 12:23:30

标签: powershell csv

#foo.csv
No, Fruit, Quality, Units, Location
1, Orange, New, 10, Village
2, Orange, Fresh, 20, City
3, Apple, New, 15, Village
4, Grapes, Fresh, 25, City
5, Apple, Fresh, 30, City
6, Apple, Fresh, 35, City

根据这些数据,我希望以下列方式输出:
水果|位置|质量|单元

我无法进一步分组(子组?)数据,我所提供的数据如下,但它不是我需要的:

Import-Csv "E:\foo.csv"  | 
Group-Object { $_.Fruit } | 
Select-Object -Property Count, 
    @{ Name = 'Fruits'; Expression = { $_.Name } }, 
    @{ Name = 'Location'; Expression = { ($_.Group | Measure-Object -Property Units -Sum).Sum } } | 
Export-Csv new.csv  -NoTypeInformation

我进一步尝试了:

Import-Csv "E:\foo.csv"  | 
Group-Object { $_.Fruit } | 
Select-Object -Property Count, 
    @{ Name = 'Fruits'; Expression = { $_.Name } }, 
    @{ Name = 'Location'; Expression = { $_.Location } },
    @{ Name = 'Quality'; Expression = { $_.Quality } },
    @{ Name = 'Units'; Expression = { ($_.Group | Measure-Object -Property Units -Sum).Sum } } | Sort-Object -Property Count | Format-Table -Auto

但数据是空白的。

1 个答案:

答案 0 :(得分:4)

您可以在同一时间按多个属性进行分组:

Import-Csv "E:\foo.csv"|
Group-Object Fruit,Location,Quality|
Select-Object @{Name='Fruit'   ;Expression={$_.Values[0]}},
              @{Name='Location';Expression={$_.Values[1]}},
              @{Name='Quality' ;Expression={$_.Values[2]}},
              @{Name='Units'   ;Expression={
                  ($_.Group|Measure-Object Units -Sum).Sum
              }}