Monitoring scripts help check if systems or services are working well. Email alerts tell you quickly if something goes wrong.
0
0
Monitoring scripts with email alerts in PowerShell
Introduction
You want to know if a server is down without checking it all the time.
You need to get notified when disk space is low on a computer.
You want to monitor if a website is reachable and get alerts if it is not.
You want to track if a scheduled task failed and get an email about it.
Syntax
PowerShell
Send-MailMessage -From <sender_email> -To <recipient_email> -Subject <subject_text> -Body <body_text> -SmtpServer <smtp_server>
Replace placeholders like <sender_email> with actual email addresses.
You may need to add credentials or use SSL depending on your SMTP server.
Examples
Sends a simple alert email about a server being down.
PowerShell
Send-MailMessage -From "alert@company.com" -To "admin@company.com" -Subject "Server Down" -Body "The server is not responding." -SmtpServer "smtp.company.com"
Checks disk space and sends an email if free space is below 10GB.
PowerShell
$diskSpace = Get-PSDrive C if ($diskSpace.Free -lt 10GB) { Send-MailMessage -From "alert@company.com" -To "admin@company.com" -Subject "Low Disk Space" -Body "Drive C has less than 10GB free." -SmtpServer "smtp.company.com" }
Sample Program
This script checks if the Windows Update service is running. If not, it sends an email alert. Otherwise, it prints a normal status message.
PowerShell
$serviceName = "wuauserv" $service = Get-Service -Name $serviceName if ($service.Status -ne "Running") { Send-MailMessage -From "alert@company.com" -To "admin@company.com" -Subject "Service Alert" -Body "Service $serviceName is not running." -SmtpServer "smtp.company.com" } else { Write-Output "Service $serviceName is running normally." }
OutputSuccess
Important Notes
Make sure your SMTP server allows sending emails from your script.
Test your email settings separately before adding them to monitoring scripts.
Use secure methods for credentials if your SMTP server requires authentication.
Summary
Monitoring scripts check system status automatically.
Email alerts notify you quickly when issues happen.
PowerShell's Send-MailMessage cmdlet sends emails easily from scripts.