问题
I am stuck trying to get meaningful output from a csv file.
The raw input looks like this.
Col1,Col2,Col3,Col4
a,2,b,z
a,2,c,x
a,1,d,y
e,1,f,s
e,2,g,t
h,1,k,r
I am trying to achieve an output of below (exclude col4) and export to a file for further reporting using PowerShell 2.
a 5 b,c,d
e 3 f,g
h 1 k
Code from my script function is:
$data = import-csv $filename.csv | Select-Object -property Col1,Col2,Col3 $view | Group Col1 | ` select Name,@{ Name="Col2Sum"; Expression = { [math]::round(($_.Group | Measure-Object -Sum Col2).Sum/60,2) } } | ` Sort "Col2Sum" -desc | ft -auto -GroupBy Col | out-file $file.txt
Where I am stuck is how to produce arrays from Col3 in one line and output them properly.
If anyone has any ideas.
回答1:
Can you try this :
$a = import-csv C:\temp\F.csv |Group-Object -Property col1 | `
% {$_.name + " " + $_.count + " " + `
($_.group | % {$i=0;$j=$_.count}{$i++ ; $_.col3 + ","*($j-$i -gt 0)})}
$a
a 3 b, c, d
e 2 f, g
h 1 k
And then
$a = import-csv C:\temp\F.csv |Group-Object -Property col1 | `
% {$_.name + " " + ($_.group | %{$i=0}{$i+=$_.col2}{$i}) + " " + `
($_.group | % {$i=0;$j=$_.count}{$i++ ; $_.col3 + ","*($j-$i -gt 0)})}
$a
a 5 b, c, d
e 3 f, g
h 1 k
来源:https://stackoverflow.com/questions/13050408/import-csv-groupby-sum