简体   繁体   中英

Powershell: Monitor CPU and RAM percentage usage and send email alert

I need to do a monitor for cpu and ram usage but about percentage in Powershell. I tried to do some things but it is weird. The code has two parts and I need to combine these parts and be able to send an email. My big problem is about email when it is not legible.

First part:

$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”
}  

Second part:

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

Can You help me how I can send an email with legible -body? Thank You very much

Try something like this

 #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

enter code here

Hope this is helpful to you and good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM