PowerShell可监控CPU使用率并触发通知:脚本每5秒检测一次,连续3次超90%即弹窗提醒;支持升级为SMTP邮件通知、日志记录、高占用进程排查及后台静默运行。
用 PowerShell 监控 CPU 使用率并触发通知
powershell 是 windows 自带的自动化工具,无需安装额外软件就能实时监控 cpu,并在超过阈值时发通知(如弹窗、邮件或日志)。关键不是“满载才报警”,而是设定合理阈值(比如持续 60 秒 >90%),避免误报。
基础监控脚本:检测高 CPU 并弹窗提醒
以下是最简可用脚本,每 5 秒检查一次 CPU 使用率,连续 3 次超过 90% 就弹出系统通知:
- 打开记事本,粘贴以下内容,保存为 CPU_Alert.ps1(注意扩展名是 .ps1)
- 右键该文件 → “使用 PowerShell 运行”(首次需先执行 Set-ExecutionPolicy RemoteSigned -Scope CurrentUser 允许本地脚本运行)
$threshold = 90
$checkIntervalSec = 5
$alertDurationSec = 60 # 持续超阈值时间(秒)
$sampleCount = [Math]::Ceiling($alertDurationSec / $checkIntervalSec)
<p>$highCPUCount = 0</p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/xiazai/skill8358" title="windows-shell-syntax"><img
src="https://img.php.cn/upload/skill/000/000/081/179198295533018.jpg" alt="windows-shell-syntax" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/xiazai/skill8358" title="windows-shell-syntax">windows-shell-syntax</a>
<p>在 Windows 上执行终端命令,或对比 Windows 与 Linux 的 Shell 语法时使用。建议先检测当前 Shell 是 PowerShell 还是 cmd.exe,再给出相应命令……</p>
</div>
<a href="/xiazai/skill8358" title="windows-shell-syntax" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div><p>while ($true) {
$cpu = Get-Counter '\Processor(_Total)\% Processor Time' -SampleInterval 1 -MaxSamples 1 |
Select-Object -ExpandProperty CounterSamples |
Select-Object -ExpandProperty CookedValue</p><pre class='brush:php;toolbar:false;'>if ($cpu -gt $threshold) {
$highCPUCount++
} else {
$highCPUCount = 0
}
if ($highCPUCount -ge $sampleCount) {
[System.Windows.Forms.MessageBox]::Show("⚠️ CPU 使用率持续过高:$([Math]::Round($cpu, 1))%", "CPU 警报", "OK", "Exclamation")
break # 或用 exit 停止,或改写为继续监控但只报一次
}
Start-Sleep -Seconds $checkIntervalSec}
升级方案:发送邮件通知(无需 Outlook)
若服务器无图形界面或需留痕,可改用 SMTP 发邮件。需提前确认邮件服务商是否支持 SMTP(如 QQ 邮箱、企业邮箱)并开启 SMTP 服务、获取授权码:
- 替换脚本中 $SMTPServer、$From、$To、$Password 等参数
- 把弹窗部分替换成:
Send-MailMessage -SmtpServer $SMTPServer -Port 587 -UseSsl -Credential $cred -From $From -To $To -Subject "CPU 警报" -Body "服务器 $(hostname) 当前 CPU:$([Math]::Round($cpu,1))%" - 注意:密码要用 ConvertTo-SecureString 处理,不能明文写在脚本里(生产环境建议用 Windows 凭据管理器存密)
实用增强建议
-
加日志记录:每次触发前写入事件日志或文本文件,方便回溯,例如:
"$(Get-Date): CPU $cpu%" | Out-File C:\Logs\CPU_Alert.log -Append -
限制进程排查:报警时顺带查占用最高的进程:
Get-Process | Sort-Object CPU -Descending | Select-Object -First 3 -Property ProcessName, CPU, Id - 后台长期运行:用 Start-Process PowerShell -ArgumentList "-WindowStyle Hidden -File C:\Scripts\CPU_Alert.ps1" 启动隐藏窗口;或转为 Windows 服务(需借助 nssm 等工具)

















