I am trying to combine several rows into one, provided that the key cell is the same. And write data from all lines with the same key to the final line.
**Before**
ID | Name | DateTime | Duration | Call_Type |
1234509 | Mike | 2020-01-02T01:22:33 | | Start_Call |
1234509 | | 2020-01-02T01:32:33 | 600 | End_call |
AFTER
ID | Name | DateTime | Duration | Start_Call | End_call |
1234509 | Mike | 2020-01-02T01:22:33 | 600 |2020-01-02T01:22:33 | 2020-01-02T01:32:33 |
Before
ID;Name;DateTime;Duration;Call_Type
1234509;Mike;2020-01-02T01:22:33;;Start_Call
1234509;;2020-01-02T01:32:33;600;End_call
After
ID;Name;Duration;Start_Call;End_call
1234509;Mike;600;2020-01-02T01:22:33;2020-01-02T01:32:33
How to use here
$csv | Group-Object ID
and get the data as in the picture?
After grouping by
IDwithGroup-Object, you can iterate each group and create a newSystem.Management.Automation.PSCustomObjectwith the properties you want to export in your output CSV file.For
IDwe simply use the grouping key.NameandDurationwe choose the first object that doesn't have a$nullor empty version of that property usingSystem.String.IsNullOrEmpty(). ForStart_CallandEnd_Callwe choose the object that has those values for theCall_Typeproperty.The filtering is done by
Where-Object. To get the first and expanded versions of the properties, we also use-Firstand-ExpandPropertyfromSelect-Object.output.csv
If you want to remove quotes from the CSV file, you can use the
-UseQuotesswitch fromExport-Csv. However, yhis does require PowerShell 7. If your using a lower PowerShell version, you can use some of the recommendations from How to remove all quotations mark in the csv file using powershell script?.