如何使用PowerShell读取性能计数器二进制文件?

如何使用PowerShell读取性能计数器二进制文件?

由于监控及报告需要,要统计性能计数器每天数值情况,确认数据库服务器的运行状况。若打开计数器填写,比较麻烦,现在统计用 powershell 来读取计数器的值。

第一阶段:Powershell 读取计数器文件并统计其中一个计数器的值

$startDate = (Get-Date).AddDays(-1).Date 
$endDate = (Get-Date).Date 
$perfPath = "D:\DataFiles\PERFMON\MSSQL_PERFMON_08240904.blg" 
 
#读取文件中的计数器名称 
$counterList = Import-Counter -Path $perfPath 
$countersNameList = $counterList[0].countersamples | % {$_.path} 
 
#筛选指定计数器和时间重新导入PS 
$counter = $countersNameList -like '*Processor Time*' 
$counterData = Import-Counter -Path $perfPath -Counter $counter | Where-Object -FilterScript {($_.Timestamp -ge $startDate) -and ($_.Timestamp -lt $endDate)} 
 
#计算日期范围内的数值统计 
$counterInfo = $counterData | Foreach-Object {$_.CounterSamples} | Measure-Object -property CookedValue -Average -Maximum 
 
#哈希表存储结果数据 
$resultTable=@{} 
$resultTable."CPU 利用率——平均" = $counterInfo.Average 
$resultTable."CPU 利用率——最大" = $counterInfo.Maximum 
 
$resultTable 

如何使用PowerShell读取性能计数器二进制文件?

第二阶段:批量统计文件中的所有计数器并导出到文件中

$startDate = (Get-Date).AddDays(-1).Date 
$endDate = (Get-Date).Date 
$perfPath = "D:\360Downloads\*.blg" 
 
#哈希表存储结果数据 
$resultTable=@{} 
 
#导入指定时间的所有计数器信息 
$counterData = Import-Counter -Path $perfPath | Where-Object -FilterScript {($_.Timestamp -ge $startDate) -and ($_.Timestamp -lt $endDate)} 
 
#所有的计数器名字 
$countersNameList = $counterData[0].countersamples | % {$_.Path} 
 
#遍历每个计数器,将计算结果存储到哈希表中 
foreach($counterName in $countersNameList) 
{ 
#$counterName = "\\hzc\system\threads" 
$counterDataOne = $counterData | Foreach-Object {$_.CounterSamples} | Where {$_.Path -like $counterName} 
$counterInfo = $counterDataOne | Measure-Object CookedValue -Average -Minimum -Maximum 
$resultTable.$($counterName+" :平均值") = $counterInfo.Average 
$resultTable.$($counterName+" :最小值") = $counterInfo.Minimum 
$resultTable.$($counterName+" :最大值") = $counterInfo.Maximum 
} 
 
#$resultTable.GetEnumerator() | sort Name | Format-Table -Auto 
#几种方法导出到文件 
$resultTable.GetEnumerator() | sort Name | Format-Table -Auto | Out-File "D:\360Downloads\PerfmonCounter.txt" 
$resultTable.GetEnumerator() | sort Name | Export-Csv -Path "D:\360Downloads\PerfmonCounter.txt" -Encoding "unicode" -Force 
$resultTable.GetEnumerator() | sort Name | Format-List | Export-Csv -Path "D:\360Downloads\PerfmonCounter.xlsx" -Encoding "unicode" -Force 

如何使用PowerShell读取性能计数器二进制文件?