使用Get-WmiObject对样本进行CPU监视

问题描述 投票:0回答:1

我正在使用Get-WmiObject cmdlet,用于监视没有安装PowerShell的服务器的平均CPU使用率,这是出于安全性要求。

$CPU = Get-WmiObject Win32_Processor -computername $computerName  | Measure-Object -property LoadPercentage -Average | Select Average


$CPULoad = $($CPU.average)                                   

if ( $CPULoad -ge $ThresholdCPU ){                                          

Write-output "High CPU usage: $CPULoad % on $computerName" 

} 
Else {

Write-output "CPU usage on $computerName is normal: $CPULoad %" 

}

当当前CPU使用率高于CPU阈值时,我的脚本正常工作。

但由于远程服务器的CPU使用率激增,我面临很多错误警报。

在阅读了cmdlet的文档后,我发现与Get-Counter cmdlet相反,Get-WmiObject没有某种SampleInterval属性。

无论如何使用Get-WmiObject来实现它,所以只有在3个有效样本之后,if标准才会成立吗?

powershell wmi
1个回答
0
投票

也许使用一个固定次数的循环可以做你想做的事情:

$maxAttempts = 3                                
for ($attempt = 0; $attempt -lt $maxAttempts; $attempt++) {
    $CPULoad = (Get-WmiObject Win32_Processor -ComputerName $computerName  | 
                Measure-Object -property LoadPercentage -Average).Average
    if ( $CPULoad -le $ThresholdCPU ) { break }
    # do nothing for x seconds and test CPU load again
    Start-Sleep -Seconds 1
}

if ($attempt -lt $maxAttempts) {
    Write-output "CPU usage on $computerName is normal: $CPULoad %" 
}
else {
    Write-output "High CPU usage: $CPULoad % on $computerName" 
}
© www.soinside.com 2019 - 2024. All rights reserved.