获取空白CSV行的百分比

时间:2016-07-01 19:35:06

标签: csv powershell

我已经获得了PowerShell脚本的一部分,该脚本导入CSV并使用Measure-Object对按主机分组的导入值进行一些数学运算。我目前正在获取与主机相关的行数,最小值,最大值和平均值。下面的代码段:

$data = Import-CSV -Path $SummaryTemp
$collection = @()
$data | Group-Object Hostname | ForEach-Object {
    $datarow = New-Object PSObject -Property @{ Hostname = $_.Name }
    $stat = $_.Group | Measure-Object -Property Latency -Minimum -Average -Maximum

    $datarow | Add-Member NoteProperty -Name "Count" -Value $stat.Count
    $datarow | Add-Member NoteProperty -Name "Minimum" -Value $stat.Minimum
    $datarow | Add-Member NoteProperty -Name "Average" -Value $stat.Average
    $datarow | Add-Member NoteProperty -Name "Maximum" -Value $stat.Maximum

    $collection += $datarow
}
$collection | Export-Csv -Path $StatsCSV -Append -NoTypeInformation -Force

导入的CSV看起来像这样:

"Hostname","Latency","DateTime"
"test1","22","2016-07-01 14:13:50"
"test2","28","2016-07-01 14:13:54"
"test1","","2016-07-01 14:14:02"
"test2","27","2016-07-01 14:14:06"

运行数学运算的值也可以是$null,因此CSV中不存在,例如上面的[test1]。我遇到的问题是,我还要计算空白行的百分比。例如,上述CSV对于test1为50%,对于test2为0%。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

一种可能的解决方案可能如下所示

...
$data | Group-Object Hostname | ForEach-Object {
    $datarow = New-Object PSObject -Property @{ Hostname = $_.Name }
    $stat = $_.Group | Measure-Object -Property Latency -Minimum -Average -Maximum
    $emptyStat = $_.Group | ? { $_.Latency.Trim().Length -eq 0 } | Measure-Object
    $emptyLinePct = "{0}%" -f ($emptyStat.Count * 100 / $stat.Count)

    $datarow | Add-Member NoteProperty -Name "Count" -Value $stat.Count
    $datarow | Add-Member NoteProperty -Name "Minimum" -Value $stat.Minimum
    $datarow | Add-Member NoteProperty -Name "Average" -Value $stat.Average
    $datarow | Add-Member NoteProperty -Name "Maximum" -Value $stat.Maximum
    $dataRow | Add-Member NoteProperty -Name "Empty" -Value $emptyLinePct

    $collection += $datarow
}
...