使用powershell对csv列数据进行分组并显示计数

ax6ht2ek  于 2023-03-08  发布在  Shell
关注(0)|答案(1)|浏览(128)

我的csv中有以下数据

"Path_Name","Lun_Number","status"
"vmhba0:C2:T0:L1","1","active"
"vmhba0:C1:T0:L1","1","active"
"vmhba1:C0:T7:L230","230","active"
"vmhba1:C0:T7:L231","231","active"
"vmhba1:C0:T7:L232","230","active"
"vmhba1:C0:T7:L235","231","active"
"vmhba1:C0:T7:L236","230","active"

我需要根据Lun_Number对数据进行分组,并创建一列以获取这些Lun_Number的计数
期望产量

"Path_Name","Lun_Number","status","Count"
"vmhba0:C2:T0:L1","1","active",    2
"vmhba0:C1:T0:L1","1","active",
"vmhba1:C0:T7:L230","230","active",3
"vmhba1:C0:T7:L231","230","active",
"vmhba1:C0:T7:L232","230","active",
"vmhba1:C0:T7:L235","231","active",2
"vmhba1:C0:T7:L236","231","active",

请让我知道我该怎么做。我尝试了group-objectsort-object,但它似乎不工作以下是生成上述csv的代码

$status_csv = Import-Csv -Path E:\pathstate.csv
$path_csv = Import-Csv -Path E:\PathInfo.csv

foreach($row in $path_csv)
{   
    $path_1 = $row.Path_Name
    $path_2 = $status_csv | where{$_.Name -match "^$path_1$" }
    [PsCustomObject]@{
    Path_Name = $path_1
    Lun_Number = $row.Lun_Number
    status = $path_2.PathState
    } | Export-Csv -Path E:\FinalReport.csv -NoTypeInformation -Append | Group-Object Lun_Number
    
}
8yparm6h

8yparm6h1#

我能看出你试图采取的方法,我认为下面这样的方法可能会有用:

$path_csv = Import-Csv 'sample.csv'
$Unique_Counts = $path_csv.Lun_Number | Group-Object | Select-Object Name,Count

这将帮助您获得可以用作Map的一部分的输出,以便稍后使用,在Map中可以动态匹配要检查的行,并可以使用它通过循环(如 $Unique_Counts)进行提取。
这意味着,如果您执行类似 $Unique_Counts[0].Count 的操作,将能够获取与其关联的Lun_Number(在数组中列为Name)。

Name Count
---- -----
1        2
230      3
231      2

如果您可以接受每行的计数,则可以使用下面这样的代码:

foreach($row in $path_csv)
{   
    $path_1 = $row.Path_Name
    [PsCustomObject]@{
    Path_Name = $path_1
    Lun_Number = $row.Lun_Number 
    status = $row.status
    count = $Unique_Counts | Where-Object {$_.name -eq $row.Lun_Number} | Select-Object -ExpandProperty Count
    } | Export-Csv $finalReport -NoTypeInformation -Append
    
}

这就给我提供了以下结果:

"Path_Name","Lun_Number","status","count"
"vmhba0:C2:T0:L1","1","active","2"
"vmhba0:C1:T0:L1","1","active","2"
"vmhba1:C0:T7:L230","230","active","3"
"vmhba1:C0:T7:L231","231","active","2"
"vmhba1:C0:T7:L232","230","active","3"
"vmhba1:C0:T7:L235","231","active","2"
"vmhba1:C0:T7:L236","230","active","3"

希望这会有所帮助,了解更多用例可能会有所帮助,但至少您可以获取所有Lun_numbers的唯一计数,只需将其放在所有行中即可。

相关问题