由于安全性要求,我正在使用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来完成该任务的,所以if条件只有在3个有效样本之后才为真?
答案 0 :(得分: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"
}