电源外壳。一个文件中的组对象用法

PowerShell. Group-object usage in one file

我正在尝试将多行合并为一行,前提是关键单元格相同。并将具有相同键的所有行的数据写入最后一行。

Example Pic

**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    | 

之后

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  |

之前

ID;Name;DateTime;Duration;Call_Type
1234509;Mike;2020-01-02T01:22:33;;Start_Call
1234509;;2020-01-02T01:32:33;600;End_call

之后

ID;Name;Duration;Start_Call;End_call
1234509;Mike;600;2020-01-02T01:22:33;2020-01-02T01:32:33

这里怎么用

$csv | Group-Object ID  

并得到如图所示的数据?

IDGroup-Object, you can iterate each group and create a new System.Management.Automation.PSCustomObject 分组后,您希望在输出 CSV 文件中导出属性。

对于ID,我们简单地使用分组键。 NameDuration 我们使用 System.String.IsNullOrEmpty() 选择第一个没有 $null 或 属性 的空版本的对象。对于 Start_CallEnd_Call,我们选择具有 Call_Type 属性 这些值的对象。

过滤由Where-Object. To get the first and expanded versions of the properties, we also use -First and -ExpandProperty from Select-Object完成。

$csv = Import-Csv -Path .\data.csv -Delimiter ";"

$groups = $csv | Group-Object -Property ID

& {
    foreach ($group in $groups)
    {
        [PSCustomObject]@{
            ID = $group.Name
            Name = $group.Group | Where-Object {-not [string]::IsNullOrEmpty($_.Name)} | Select-Object -First 1 -ExpandProperty Name
            Duration = $group.Group | Where-Object {-not [string]::IsNullOrEmpty($_.Duration)} | Select-Object -First 1 -ExpandProperty Duration
            Start_Call = $group.Group | Where-Object {$_.Call_Type -eq "Start_Call"} | Select-Object -First 1 -ExpandProperty DateTime
            End_Call = $group.Group | Where-Object {$_.Call_Type -eq "End_Call"} | Select-Object -First 1 -ExpandProperty DateTime
        }
    }
} | Export-Csv -Path .\output.csv -Delimiter ";" -NoTypeInformation

output.csv

"ID";"Name";"Duration";"Start_Call";"End_Call"
"1234509";"Mike";"600";"2020-01-02T01:22:33";"2020-01-02T01:32:33"

如果要从 CSV 文件中删除引号,可以使用 Export-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? 中的 -UseQuotes 开关。