简体   繁体   中英

Transposing a CSV file using PowerShell

I have a CSV file that has a static number of columns (with headers) and a dynamic number of rows and I need convert it to another CSV which has a static number of rows and a dynamic number of columns (with or without headers).

Here is an example of what the before and after would look like in a spreadsheet. Please keep in mind that the top section would represent my input data and the bottom section is the desired state.

CSV电子表格数据

Of course this is a small subset as I could have a user that has 50 groups and a user which may only have 1 group associated with it. This leaves me with not knowing the number of columns in advance so it has to be dynamic.

I have tried using what I found on this post , but I am running into an issue trying to modify the code to fit my needs. The closest I have been able to do is create a row for each unique user ID but instead of having the corresponding group names in columns next to each user, they are set as the headers and no values for the users.

意外的当前结果

If you don't require headers or defined columns you could simply collect the values from the second column in a hashtable of arrays where you use the values from the first column as keys:

$data = @{}
Import-Csv 'C:\path\to\input.csv' | ForEach-Object {
    $data[$_.UserID] += @($_.GroupName)
}

Then you can export the data to a text file like this:

$data.Keys | ForEach-Object {
    $_ + ',' + ($data[$_] -join ',')
} | Set-Content 'C:\path\to\output.txt'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM