问题
need some help with powershell and manipulating csv files, as I'm a newbie trying to learn.
I've got a .csv file with several columns, for now lets refer to them as A, B, C, D In column 'A' I have URLs, Column 'B' I have Groups, C and D are of o importance for this example.
so as far as the values in the cells below each column, obviously the Values of URL are tied to the Value of those under Group Column 'B'.
Sample csv:
URL,Groups,x,y
test1.org,TestGroup,xxx,yyy
test2.org,TestGroup,xxx,yyy
Test3.com,TestGroup,xxx,yyy
Check.com,CheckGroup,xxx,yyy
Random.1.com,RandomGroup,xxx,yyy
random.22.org,RandomGroup,xxx,yyy
So what I'm trying to do is group these in a way that it looks like this:
Groups,URL,x,y
TestGroup,"test1.org,test2.org,test3.org",xxx,yyy
CheckGroup,Check.com,xxx,yyy
RandomGroup,"Random.1.com,random.22.org",xxx,yyy
I tried the following:
$Dir = "FileLocation\Data"
$Data1 = import-csv $Dir\my.csv
$Data = $Data1 | Select Groups, URL | Group-Object Groups
$Data | export-cdv $Dir\result.csv
This results in a table that does not work for me as it turns the grouping into an array.
I want to be able to sort unique by group on the original csv and import the values of the Group's URL as they relate in the same cell separated by commas.
Thanks for the help.
回答1:
Looks like a good case for a hashtable magic, create a hashtable and append to it, using Group Column as a key.
$data = import-csv 'path'
$hashtable = @{}
foreach ($item in $data) { $hashtable[$($item.Groups)] += "$($item.URL), " }
the only downside is that there is an extra comma at the end of each key.
来源:https://stackoverflow.com/questions/42539117/powershell-to-group-items-separated-by-commas-as-they-relate-to-another-value-on