Bird
Raised Fist0
PowerShellscripting~10 mins

Monitoring scripts with email alerts in PowerShell - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Monitoring scripts with email alerts
Start Script
↓
Check System Metric
↓
Is Metric OK?
No→Send Email Alert
↓
Log Alert Sent
↓
Wait/Delay
↓
Repeat or End
The script starts, checks a system metric, sends an email if the metric is bad, logs the alert, waits, then repeats or ends.
Execution Sample
PowerShell
if ($cpuUsage -gt 80) {
  Send-MailMessage -To 'admin@example.com' -Subject 'High CPU Alert' -Body "CPU usage is $cpuUsage%" -SmtpServer 'smtp.example.com'
}
This script checks if CPU usage is above 80%, then sends an email alert with the current CPU usage.
Execution Table
StepActionCondition/EvaluationResult/Output
1Get CPU usage$cpuUsage = 75CPU usage recorded as 75%
2Check if $cpuUsage > 8075 > 80False, no email sent
3Wait before next checkN/APause for 60 seconds
4Get CPU usage$cpuUsage = 85CPU usage recorded as 85%
5Check if $cpuUsage > 8085 > 80True, proceed to send email
6Send email alertSend-MailMessage executedEmail sent to admin@example.com
7Log alertWrite to log fileAlert logged with timestamp
8Wait before next checkN/APause for 60 seconds
9Repeat or endScript loops or stopsScript ready for next iteration or exit
💡 Script stops when manually terminated or after set iterations
Variable Tracker
VariableStartAfter Step 1After Step 4Final
$cpuUsageundefined758585
Email SentNoNoYesYes
Log EntryNoneNoneCreatedCreated
Key Moments - 3 Insights
Why is no email sent when CPU usage is 75%?
Because the condition $cpuUsage > 80 is false at step 2, so the script skips sending the email.
What triggers the email alert to be sent?
When the CPU usage exceeds 80%, as shown at step 5, the condition becomes true and the email is sent.
Why does the script wait after checking the CPU usage?
The wait at steps 3 and 8 prevents the script from running continuously without pause, allowing time between checks.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of $cpuUsage at step 4?
A75
B85
C80
DUndefined
💡 Hint
Check the 'Condition/Evaluation' column at step 4 in the execution table.
At which step does the script send the email alert?
AStep 6
BStep 5
CStep 2
DStep 7
💡 Hint
Look for the 'Send email alert' action in the 'Action' column.
If the CPU usage never exceeds 80%, what happens to the 'Email Sent' variable?
AIt changes to Yes
BIt becomes undefined
CIt remains No
DIt logs an error
💡 Hint
Refer to the variable_tracker for 'Email Sent' values when CPU usage is below threshold.
Concept Snapshot
Monitoring scripts check system metrics regularly.
If a metric crosses a threshold, an email alert is sent.
Use Send-MailMessage in PowerShell to send emails.
Include logging and wait times to avoid spamming.
Loop the script for continuous monitoring.
Full Transcript
This visual execution shows a PowerShell monitoring script that checks CPU usage. It starts by reading the CPU usage value. If the usage is above 80%, it sends an email alert to the administrator and logs the alert. If not, it waits before checking again. The script repeats this cycle until stopped. Variables like $cpuUsage and Email Sent track the system state and alert status. Key moments include understanding when emails are sent and why the script waits between checks. The quiz tests knowledge of variable values and script behavior at specific steps.

Practice

(1/5)
1. What is the main purpose of using email alerts in PowerShell monitoring scripts?
easy
A. To notify administrators immediately when a problem occurs
B. To slow down the script execution
C. To store logs locally on the computer
D. To increase the script's runtime

Solution

  1. Step 1: Understand monitoring scripts

    Monitoring scripts check system health or status automatically without manual checks.
  2. Step 2: Role of email alerts

    Email alerts send notifications immediately when an issue is detected, so admins can act fast.
  3. Final Answer:

    To notify administrators immediately when a problem occurs -> Option A
  4. Quick Check:

    Alerts = Notify admins fast [OK]
Hint: Email alerts = instant problem notification [OK]
Common Mistakes:
  • Thinking email alerts slow scripts
  • Confusing alerts with local log storage
  • Assuming alerts increase runtime
2. Which of the following is the correct syntax to send an email alert using PowerShell's Send-MailMessage cmdlet?
easy
A. Send-MailMessage -Sender 'admin@example.com' -Receiver 'user@example.com' -Title 'Alert' -Content 'Issue detected' -Server 'smtp.example.com'
B. Send-Mail -From 'admin@example.com' -To 'user@example.com' -Subject 'Alert' -Body 'Issue detected' -Server 'smtp.example.com'
C. Send-MailMessage -From 'admin@example.com' -To 'user@example.com' -Subject 'Alert' -Body 'Issue detected' -SmtpServer 'smtp.example.com'
D. Send-Email -From 'admin@example.com' -To 'user@example.com' -Subject 'Alert' -Body 'Issue detected' -SmtpServer 'smtp.example.com'

Solution

  1. Step 1: Identify correct cmdlet and parameters

    The correct cmdlet is Send-MailMessage with parameters -From, -To, -Subject, -Body, and -SmtpServer.
  2. Step 2: Check each option's syntax

    Send-MailMessage -From 'admin@example.com' -To 'user@example.com' -Subject 'Alert' -Body 'Issue detected' -SmtpServer 'smtp.example.com' uses correct cmdlet and parameter names. Others use incorrect cmdlet names or parameter names.
  3. Final Answer:

    Send-MailMessage -From 'admin@example.com' -To 'user@example.com' -Subject 'Alert' -Body 'Issue detected' -SmtpServer 'smtp.example.com' -> Option C
  4. Quick Check:

    Send-MailMessage + correct params = A [OK]
Hint: Send-MailMessage with -From, -To, -Subject, -Body, -SmtpServer [OK]
Common Mistakes:
  • Using wrong cmdlet names like Send-Mail or Send-Email
  • Incorrect parameter names like -Sender or -Receiver
  • Missing -SmtpServer parameter
3. What will be the output of this PowerShell snippet?
if ((Get-Process -Name 'notepad' -ErrorAction SilentlyContinue) -eq $null) {
  Send-MailMessage -From 'alert@example.com' -To 'admin@example.com' -Subject 'Notepad not running' -Body 'Please start Notepad.' -SmtpServer 'smtp.example.com'
  'Alert sent'
} else {
  'Notepad is running'
}
medium
A. No output because Send-MailMessage blocks output
B. 'Alert sent' if Notepad is not running, else 'Notepad is running'
C. Syntax error due to missing parentheses
D. Always 'Alert sent' regardless of Notepad status

Solution

  1. Step 1: Understand the condition

    The script checks if Notepad process exists; if not found, condition is true.
  2. Step 2: Analyze the if-else branches

    If Notepad is not running, it sends an email and outputs 'Alert sent'. Otherwise, outputs 'Notepad is running'.
  3. Final Answer:

    'Alert sent' if Notepad is not running, else 'Notepad is running' -> Option B
  4. Quick Check:

    Process check controls output [OK]
Hint: Check process null means send alert, else normal message [OK]
Common Mistakes:
  • Assuming Send-MailMessage blocks output
  • Thinking condition always true
  • Confusing error handling with syntax error
4. You wrote this script to send an email alert if disk space is low:
$freeSpace = (Get-PSDrive C).Free
if ($freeSpace -lt "100MB") {
  Send-MailMessage -From 'alert@example.com' -To 'admin@example.com' -Subject 'Low Disk Space' -Body 'Disk space below 100MB' -SmtpServer 'smtp.example.com'
}

But no email is sent even when disk space is low. What is the likely problem?
medium
A. The if condition should use -gt instead of -lt
B. Get-PSDrive does not return Free space
C. Send-MailMessage requires -Port parameter
D. 100MB is not a valid size unit in PowerShell comparison

Solution

  1. Step 1: Check the size comparison

    PowerShell does not recognize '100MB' as a valid number; it must be converted to bytes.
  2. Step 2: Understand Get-PSDrive output

    Get-PSDrive returns Free space in bytes as a number, so comparing to '100MB' string fails silently.
  3. Final Answer:

    100MB is not a valid size unit in PowerShell comparison -> Option D
  4. Quick Check:

    Size units must be numeric bytes [OK]
Hint: Use numeric bytes, not '100MB' string in comparisons [OK]
Common Mistakes:
  • Assuming Get-PSDrive Free is not available
  • Thinking Send-MailMessage needs -Port always
  • Confusing less than and greater than operators
5. You want to create a PowerShell monitoring script that checks CPU usage every 5 minutes and sends an email alert if usage exceeds 80%. Which approach correctly implements this?
hard
A. Use a loop with Start-Sleep 300, check CPU with Get-Counter, send email if over 80%
B. Run Get-Counter once, then send email immediately without looping
C. Use a scheduled task to run the script every hour, check CPU, send email if over 80%
D. Use a loop with Start-Sleep 60, check CPU once, then exit

Solution

  1. Step 1: Understand monitoring frequency

    Checking CPU every 5 minutes requires a loop with a 300-second (5-minute) sleep between checks.
  2. Step 2: Use Get-Counter and conditional email

    Get-Counter can measure CPU usage; if usage > 80%, Send-MailMessage sends alert.
  3. Step 3: Evaluate options

    Use a loop with Start-Sleep 300, check CPU with Get-Counter, send email if over 80% uses loop with Start-Sleep 300 and conditional email, matching requirements. Others either run once or wrong intervals.
  4. Final Answer:

    Use a loop with Start-Sleep 300, check CPU with Get-Counter, send email if over 80% -> Option A
  5. Quick Check:

    Loop + 5 min sleep + CPU check + email = C [OK]
Hint: Loop with 300s sleep and conditional email alert [OK]
Common Mistakes:
  • Running check only once without loop
  • Using wrong sleep duration
  • Confusing scheduled task frequency with script loop
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard