【问题标题】:Powershell: Monitor CPU and RAM percentage usage and send email alertPowershell:监控 CPU 和 RAM 百分比使用率并发送电子邮件警报
【发布时间】:2021-12-29 09:00:27
【问题描述】:

我需要监控 cpu 和 ram 的使用情况,但要监控 Powershell 中的百分比。 我试图做一些事情,但这很奇怪。 该代码有两个部分,我需要将这些部分组合起来并能够发送电子邮件。 我最大的问题是电子邮件不清晰。

第一部分:

$repeat_count = 3
$cpu_threshold = 80
$sleep_interval = 5
$hit = 0
foreach($turn in 1..$repeat_count) {
$cpu = (gwmi -class Win32_Processor).LoadPercentage
#write-host “CPU is $cpu`%”
If($cpu -ge $cpu_threshold) {
$hit = $hit+1
}
start-sleep $sleep_interval
}

if($hit -eq 3) {
write-host “CPU is more then $cpu_threshold`%”

Send-MailMessage -From user01@fabrikam.com -To user02@fabrikam.com -Subject “CPU2 is more then $cpu_threshold`%” -Body “CPU is $cpu`%” -Encoding UTF8 -SmtpServer smtp@fabrikam.com

} else {
write-host “CPU is under the limit”
}  

第二部分:

Get-Counter -ErrorAction SilentlyContinue '\Process(*)\% Processor Time' | Select-Object -ExpandProperty countersamples| Select-Object -Property instancename, cookedvalue| ? {$_.instanceName -notmatch "^(idle|_total|system)$"} | Sort-Object -Property cookedvalue -Descending| Select-Object -First 5| ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100/$env:NUMBER_OF_PROCESSORS).toString('P')}} -AutoSize

你能帮我如何发送一封带有清晰 -body 的电子邮件吗? 非常感谢

【问题讨论】:

  • 附加ConvertTo-Html 以获得清晰的电子邮件body。否则,如果您需要汇总一些结果,您可以查看ConvertTo-HtmlTable
  • 已经内置了性能监视器,它可以发送电子邮件警报。为什么不使用它?
  • 为什么不使用 SCOM?

标签: powershell scripting


【解决方案1】:

试试这样的

#create an html email body 
 $body = @"
    <html>
        <body style="font-family:calibri"> 
        <b>Create your fancy Html email template here</b>
            <b>$table</b>
                </body>
    </html>
"@     


#Run your get command to populate your table var with info and convert to HTML
$table = Get-Counter -ErrorAction SilentlyContinue '\Process(*)\% Processor Time' | Select-Object -ExpandProperty countersamples| Select-Object -Property instancename, cookedvalue| ? {$_.instanceName -notmatch "^(idle|_total|system)$"} | Sort-Object -Property cookedvalue -Descending| Select-Object -First 5| select-object InstanceName,@{L='CPU';E={($_.Cookedvalue/100/$env:NUMBER_OF_PROCESSORS).toString('P')}} | convertto-html -Fragment
#this will send your HTML email.  
Send-MailMessage -From user01@fabrikam.com -To user02@fabrikam.com -Subject “CPU2 is more then $cpu_threshold`%” -body $body -SmtpServer smtp@fabrikam.com

在此处输入代码

希望这对你有帮助,祝你好运。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-10
    • 1970-01-01
    • 1970-01-01
    • 2016-07-24
    • 1970-01-01
    相关资源
    最近更新 更多