PowerShell is very powerfull and you can automate most of your daily tasks. One of the best task that I like to automate is to monitor system performance and send email alerts. Here is a sample script but you can customize based on your needs.
$cpu = Get-Counter ‘\Processor(_Total)\% Processor Time’
$cpuValue = $cpu.CounterSamples.CookedValue
if ($cpuValue -gt 90)
{
Send-MailMessage -From “john@abc.com” -To “reporting@abc.com” -Subject “High CPU Usage Alert” -Body “CPU usage is above 90%: $cpuValue%” -SmtpServer “smtp.abc.com”
}
Technical Explanation of script
Below is the technical explanation of what each code and argument in the above powershell script does.
$cpu = Get-Counter ‘\Processor(_Total)\% Processor Time’
This line uses the Get-Counter
cmdlet to retrieve performance data. Specifically, it gets the percentage of processor time used by the total processor(s) on the machine (_Total
). This is a performance counter that measures CPU usage.
$cpuValue = $cpu.CounterSamples.CookedValue
Here, the script extracts the cooked value of the CPU usage from the CounterSamples
property of the object returned by Get-Counter
. The CookedValue
represents the percentage of CPU usage in a human-readable form.
if ($cpuValue -gt 90)
This line checks if the CPU usage is greater than 90%. The script will proceed to send an alert if this condition is true.
Send-MailMessage -From “john@abc.com” -To “reporting@abc.com” -Subject “High CPU Usage Alert” -Body “CPU usage is above 90%: $cpuValue%” -SmtpServer “smtp.abc.com”
If the CPU usage is above 90%, the script sends an email alert using the Send-MailMessage
cmdlet.
- From: Specifies the sender’s email address (
john@abc.com
). - To: Specifies the recipient’s email address (
reporting@abc.com
). - Subject: The subject line of the email, indicating a high CPU usage alert.
- Body: The body of the email, which includes the actual CPU usage percentage.
- SmtpServer: The SMTP server (
smtp.abc.com
) used to send the email.
This script monitors the CPU usage of a system and sends an email alert to a specified recipient if the CPU usage exceeds 90%. This kind of script can be used in system administration to monitor server health and performance, ensuring that administrators are alerted to potential issues promptly