问题描述
我正在尝试编写一个脚本,该脚本使用 OpenHardwareMonitor 获取 cpu 温度,并在给定持续时间内平均高于特定阈值时发出警报。
获取当前温度工作正常,但我正在努力将它们平均化,因为在某些系统上可能有一个或多个 cpu,所以我不能只记录每分钟的温度并除以经过的分钟数,下面是我得到的最好的(不起作用),请一些好心人帮我看看我哪里出错了?
$tempThreshold = 80 # Will alert if average temperature is above this
$minutes = 3 # Duration in minutes to test for
start-process "$env:SystemRoot\TEMP\OpenHardwareMonitor\openhardwaremonitor.exe"
# Loop each minute
for ($i=1; $i -le $minutes; $i++) {
$arrSensors=@{}
if ((Get-WmiObject -Namespace "Root\OpenHardwareMonitor" -Query "SELECT * FROM Sensor WHERE Sensortype='Temperature'" | ? {$_.Name -match 'cpu Package'}).value) {
Get-WmiObject -Namespace "Root\OpenHardwareMonitor" -Query "SELECT * FROM Sensor WHERE Sensortype='Temperature'" | ? {$_.Name -Match "cpu Package"} | % {$arrSensors[$_.Name]=$_.Value}
} else {
Get-WmiObject -Namespace "Root\OpenHardwareMonitor" -Query "SELECT * FROM Sensor WHERE Sensortype='Temperature'" | ? {$_.Identifier -match 'cpu/'} | % {$arrSensors[$_.Name]=$_.Value}
}
$temps = foreach ($sensor in $arrSensors.getEnumerator()) {
Start-Sleep -Seconds 60
$temp = $temp+$sensor.value
}
}
# Alert if average above threshold
if ($temps/$minutes -gt $tempThreshold) {
Write-Host "Alert function here"
}
解决方法
我也在寻找监控 Windows 上的 CPU 温度。我的后端是带有 influxdb 的 grafana。使用 ohm 和 wmi 非常消耗 CPU,我发现 https://github.com/nickbabcock/OhmGraphite#influxdb-configuration。这个应用程序基于 ohm,但将数据直接发送到 influxdb(不需要昂贵的 wmi 调用)。也许这对你来说也很有趣。使用 grafana,您可以平均该值并在那里设置阈值。
但是 - 也许这不是您的选择,所以这里的脚本使用欧姆应用程序获得平均值。 这个脚本的缺点是,脚本运行了 2 分钟 - 所以你不会每分钟都收到警报(除非你用一分钟的 appart 运行它两次(可以使用计划任务轻松设置)。
$tempThreshold = 80 # Will alert if average temperature is above this
$minutes = 3 # Duration in minutes to test for
start-process "$env:SystemRoot\TEMP\OpenHardwareMonitor\openhardwaremonitor.exe"
$counter = 0
$sum = 0
while($counter -lt $minutes) {
$cpuArray = Get-WmiObject -Namespace "Root\OpenHardwareMonitor" -Query "SELECT * FROM Sensor WHERE Sensortype='Temperature'"
if($cpuArray | where name -like 'cpu package*') {
$cpuTempArray = $cpuArray | where name -like 'cpu package*'
} else {
$cpuTempArray = $cpuArray | where name -like 'cpu core*'
}
foreach($cpuTemp in $cpuTempArray){
$sum += $cpuTemp.value
}
$counter++
if($counter -ne $minutes) {
Start-Sleep -Seconds 60
}
}
$average = $sum/($counter*$cpuTempArray.Count)
# Alert if average above threshold
if($average -gt $tempThreshold) {
Write-Host "Alert function here"
}
,
正如我的另一个答案所提到的,另一个脚本运行一次,恕我直言不能被视为“监视”——就像在“达到阈值时发出警报”一样——就像每分钟一样。
以下脚本无限循环运行。它收集设定的数据量 (kubectl kustomize . | kubectl apply -f -
) 作为每分钟的平均值。您可能想要更改它以将所有 CPU 的最大值存储在 $minutes
中,然后取其平均值。
$valueArray