Learn how to build a robust PowerShell monitoring and alerting system with practical examples. This guide covers what to monitor, how to set up alert rules, generate dashboards, and handle incident response using only PowerShell and native Windows tools.
Intro
PowerShell is a powerful tool for automating and managing Windows environments, but its true potential is unlocked when it is used for monitoring and alerting. By leveraging PowerShell's ability to query system information, parse logs, and send notifications, you can build a custom monitoring solution tailored to your needs without relying on expensive third-party tools. This guide provides practical, step-by-step instructions to set up monitoring for critical metrics, define alert rules, create dashboards, and handle incidents effectively. Whether you are a developer, DevOps consultant, or part of a technical startup team, you will learn how to implement a lightweight yet robust monitoring system using only PowerShell and native Windows features.
Version and Environment Inventory
Before implementing monitoring, establish a clear picture of your environment. This section outlines the prerequisites, the topology, and the PowerShell version required.
Prerequisites
- Windows 10/11 or Windows Server 2016 or later.
- PowerShell 5.1 or PowerShell 7.0+ (cross-platform).
- Administrative privileges for certain commands (e.g., accessing event logs, performance counters).
- Access to an SMTP server or a webhook endpoint (e.g., Slack, Teams) for alert delivery.
- A simple text editor or PowerShell ISE for scripting.
Checking PowerShell Version
Run the following to check your PowerShell version:
$PSVersionTable.PSVersion
Expected output example:
Major Minor Build Revision
----- ----- ----- --------
7 3 4 0
If you have an older version, consider upgrading to PowerShell 7 for better performance and features.
Environment Topology
A typical monitoring setup consists of:
- Monitored hosts: Machines whose metrics you want to track (e.g., CPU, memory, disk, services).
- Monitoring server: A central machine that collects data and sends alerts (could be one of the hosts).
- Alerting channel: Email, webhook, or log file for notifications.
For simplicity, this guide assumes a single Windows machine acting as both the monitored host and the monitoring server, but the concepts scale to multiple machines using PowerShell Remoting.
Designing Your Monitoring Strategy
Before writing scripts, decide what to monitor and what thresholds warrant an alert. A good monitoring strategy focuses on leading indicators of problems, not just lagging symptoms. Start with a small set of critical metrics that directly impact user experience or system stability.
Selecting Metrics
For a Windows server or workstation, the following metrics provide a solid baseline:
| Metric | What It Tells You | Common Threshold |
|---|---|---|
| CPU usage | Overall processor load | Alert if > 80% for 5 minutes |
| Available memory | Memory pressure | Alert if < 10% free |
| Free disk space on system drive | Risk of disk full | Alert if < 10% free or < 5 GB |
| Service status | Critical service stopped | Alert if not Running |
| Event log errors | Application failures | Alert on critical errors in last hour |
These are starting points. Adjust thresholds based on observed baselines in your environment. For example, a database server may normally run at 70% CPU during business hours, so an 80% threshold might be too aggressive. Collect data for a week before setting final alert thresholds.
Defining Alert Severity
Assign each alert a severity level to prioritize response:
- Critical: Immediate action required. Service down, disk full, CPU sustained at 100%.
- Warning: Potential issue. Disk space below 15%, CPU above 70% for 15 minutes.
- Info: Not an alert, but useful for dashboards and trend analysis.
In the scripts, we will use these severity labels to filter alerts and avoid alert fatigue.
Safe Configuration Path
Implement monitoring in a scoped, controlled manner. Avoid global changes; use dedicated scripts and scheduled tasks. This approach minimizes risk and allows easy rollback.
Step 1: Create a Monitoring Folder
Create a dedicated folder for scripts, logs, and configuration:
New-Item -ItemType Directory -Path "C:\Monitoring" -Force
This folder will contain all monitoring scripts, configuration files, and generated logs. Keeping everything in one place makes it easy to back up, version control, and remove if needed.
Step 2: Write a Reusable Monitoring Function
Create a function that checks a specific metric and returns a status object. Save as C:\Monitoring\Get-CpuUsage.ps1:
function Get-CpuUsage {
$cpu = Get-Counter '\Processor(_Total)\% Processor Time'
$cpuValue = $cpu.CounterSamples[0].CookedValue
[PSCustomObject]@{
Timestamp = Get-Date
Metric = 'CPU Usage'
Value = $cpuValue
Unit = '%'
Threshold = 80
Status = if ($cpuValue -gt 80) { 'Critical' } else { 'OK' }
}
}
This function reads the current CPU usage and compares it to a threshold. The returned object includes all the information needed for further processing: timestamp, metric name, value, unit, threshold, and status. For a more robust function, consider these enhancements:
- Accept parameters for threshold and sample interval.
- Return a collection of samples over a short period to avoid false positives from momentary spikes.
- Include additional properties like
ComputerNamefor multi-host monitoring.
Here is an improved version with parameterization and sampling:
function Get-CpuUsage {
param(
[int]$Threshold = 80,
[int]$SampleSeconds = 5
)
$samples = Get-Counter '\Processor(_Total)\% Processor Time' -SampleInterval 1 -MaxSamples $SampleSeconds
$avgCpu = ($samples.CounterSamples | Measure-Object -Property CookedValue -Average).Average
[PSCustomObject]@{
Timestamp = Get-Date
Metric = 'CPU Usage (5s avg)'
Value = [math]::Round($avgCpu, 2)
Unit = '%'
Threshold = $Threshold
Status = if ($avgCpu -gt $Threshold) { 'Critical' } else { 'OK' }
}
}
This version averages CPU samples over 5 seconds, reducing the chance of a false alert from a brief spike.
Step 3: Configure Alert Rules
Create a script to evaluate the metric and send an alert if needed. Example: C:\Monitoring\Check-CpuAlert.ps1:
# Load the function
. C:\Monitoring\Get-CpuUsage.ps1
$result = Get-CpuUsage -Threshold 80
if ($result.Status -eq 'Critical') {
$subject = "CPU Alert on $env:COMPUTERNAME"
$body = "CPU usage is $($result.Value)% (threshold: $($result.Threshold)%) at $($result.Timestamp)"
# Replace with your SMTP details
Send-MailMessage -To '[email protected]' -From '[email protected]' -Subject $subject -Body $body -SmtpServer 'smtp.example.com'
Write-Host "Alert sent: $subject"
} else {
Write-Host "CPU usage normal: $($result.Value)%"
}
Note that Send-MailMessage is deprecated in PowerShell 7 and may not be available in future versions. Consider using Send-MailKitMessage from the MailKit module or a webhook to Slack/Teams as a modern alternative. For a simple webhook example:
$webhookUri = 'https://hooks.slack.com/services/YOUR/WEBHOOK/URL'
$payload = @{ text = "$subject - $body" } | ConvertTo-Json
Invoke-RestMethod -Uri $webhookUri -Method Post -Body $payload -ContentType 'application/json'
This avoids SMTP configuration and integrates with modern collaboration tools.
Step 4: Schedule the Check
Use Task Scheduler to run the check every 5 minutes:
$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-NoProfile -WindowStyle Hidden -File "C:\Monitoring\Check-CpuAlert.ps1"'
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 5)
Register-ScheduledTask -TaskName 'CPU Monitor' -Action $action -Trigger $trigger -Description 'Checks CPU usage and alerts if high' -User 'SYSTEM'
This creates a scheduled task that runs as SYSTEM. Important considerations:
- Running as SYSTEM means the script has high privileges; ensure your scripts are secure and not writable by unprivileged users.
- The task will run every 5 minutes indefinitely once triggered. You can stop it by disabling or unregistering the task.
- For tasks that need network access (e.g., sending webhooks), ensure the SYSTEM account has outbound internet access or use a service account with appropriate permissions.
To run the task with a specific user account, omit the -User 'SYSTEM' and provide credentials when registering:
Register-ScheduledTask -TaskName 'CPU Monitor' -Action $action -Trigger $trigger -Description 'Checks CPU usage' -User 'DOMAIN\monitoring' -Password (Read-Host -AsSecureString 'Password')
Step 5: Implement Other Metrics
Repeat the pattern for other important metrics: memory usage, disk space, service status, etc. Create a modular approach with a main script that calls each check. Here are examples for memory and disk:
Memory check function (C:\Monitoring\Get-MemoryUsage.ps1):
function Get-MemoryUsage {
param([int]$ThresholdPercent = 10) # Alert if free memory below 10%
$os = Get-CimInstance Win32_OperatingSystem
$totalMemory = $os.TotalVisibleMemorySize # in KB
$freeMemory = $os.FreePhysicalMemory # in KB
$freePercent = ($freeMemory / $totalMemory) * 100
[PSCustomObject]@{
Timestamp = Get-Date
Metric = 'Memory Free %'
Value = [math]::Round($freePercent, 2)
Unit = '%'
Threshold = $ThresholdPercent
Status = if ($freePercent -lt $ThresholdPercent) { 'Critical' } else { 'OK' }
}
}
Disk space check function (C:\Monitoring\Get-DiskSpace.ps1):
function Get-DiskSpace {
param(
[string]$DriveLetter = 'C:',
[int]$ThresholdGB = 10
)
$disk = Get-PSDrive -Name $DriveLetter.TrimEnd(':')
$freeGB = [math]::Round($disk.Free / 1GB, 2)
[PSCustomObject]@{
Timestamp = Get-Date
Metric = "Free disk space on $DriveLetter"
Value = $freeGB
Unit = 'GB'
Threshold = $ThresholdGB
Status = if ($freeGB -lt $ThresholdGB) { 'Critical' } else { 'OK' }
}
}
Create a main orchestration script that runs all checks and handles alerts uniformly:
# C:\Monitoring\Run-AllChecks.ps1
. C:\Monitoring\Get-CpuUsage.ps1
. C:\Monitoring\Get-MemoryUsage.ps1
. C:\Monitoring\Get-DiskSpace.ps1
$results = @()
$results += Get-CpuUsage -Threshold 80
$results += Get-MemoryUsage -ThresholdPercent 10
$results += Get-DiskSpace -DriveLetter 'C:' -ThresholdGB 10
$critical = $results | Where-Object Status -eq 'Critical'
if ($critical.Count -gt 0) {
$body = $critical | Format-Table -AutoSize | Out-String
# Send alert using email or webhook as before
Send-Alert -Subject "Critical alerts on $env:COMPUTERNAME" -Body $body
}
This approach keeps each check modular and makes it easy to add or remove metrics.
Verification and Diagnostics
After setting up monitoring, verify that it works as expected. Use these diagnostics to confirm data collection, alerting, and scheduling.
Verify CPU Usage Function
Run the function manually:
. .\Get-CpuUsage.ps1
Get-CpuUsage | Format-Table
Expected output:
Timestamp Metric Value Unit Threshold Status
--------- ------ ----- ---- --------- ------
10/25/2023 10:15:32 AM CPU Usage (5s avg) 23.5 % 80 OK
If you get errors, check that the performance counter name is correct. You can list all counter paths with Get-Counter -ListSet * | Select-Object -ExpandProperty Paths.
Test Alert Script
To test the alert without waiting for a real threshold breach, temporarily modify the threshold in the function or use a mock value. For example, call the function with a low threshold:
$result = Get-CpuUsage -Threshold 1
$result # Should show Status = Critical
Then run the alert script but replace the actual send command with a write to console or file:
# In Check-CpuAlert.ps1, temporarily comment out Send-MailMessage and add:
Write-Host "TEST ALERT: $subject - $body"
This avoids spamming recipients during testing.
Check Scheduled Task
Verify the task is registered and its status:
Get-ScheduledTask -TaskName 'CPU Monitor'
Check last run result:
(Get-ScheduledTaskInfo -TaskName 'CPU Monitor').LastTaskResult
A result of 0 indicates success. If it is not 0, check the task's history in Event Viewer under Applications and Services Logs > Microsoft > Windows > TaskScheduler > Operational for error details. To manually run the task:
Start-ScheduledTask -TaskName 'CPU Monitor'
Diagnostic Logging
Add logging to your scripts for troubleshooting. At the top of your script, redirect output to a log file:
Start-Transcript -Path "C:\Monitoring\log.txt" -Append
End with Stop-Transcript. Then inspect the log after running. You can also add explicit logging of alerts to a CSV file for historical analysis:
$result | Export-Csv -Path "C:\Monitoring\metrics.csv" -Append -NoTypeInformation
This creates a time-series dataset useful for baselining and capacity planning.
Building a Dashboard
While alerts notify you of problems, a dashboard gives you a real-time view of system health. PowerShell can generate a simple HTML dashboard that refreshes periodically. Here is an example that collects metrics and produces a single HTML file:
# C:\Monitoring\New-Dashboard.ps1
$metrics = @()
$metrics += Get-CpuUsage -Threshold 80
$metrics += Get-MemoryUsage -ThresholdPercent 10
$metrics += Get-DiskSpace -DriveLetter 'C:' -ThresholdGB 10
$html = $metrics | ConvertTo-Html -Property Timestamp, Metric, Value, Unit, Threshold, Status -Fragment
$htmlHeader = "<h1>System Health Dashboard</h1><p>Generated at $(Get-Date)</p>"
$htmlBody = $htmlHeader + $html
# Add CSS for better styling (optional)
$css = @"
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
table { border-collapse: collapse; width: 100%; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background-color: #f2f2f2; }
.critical { color: red; font-weight: bold; }
</style>
"@
$fullHtml = "<html><head>$css</head><body>$htmlBody</body></html>"
$fullHtml | Out-File -FilePath "C:\Monitoring\dashboard.html" -Encoding UTF8
Open dashboard.html in a browser to see the dashboard. Schedule this script to run every 5 minutes using Task Scheduler to keep the dashboard current. Note that ConvertTo-Html is simple; for more advanced dashboards, consider using tools like Grafana with PowerShell as a data source.
Failure Modes and Recovery
Even a simple monitoring setup can fail. Understand common failure modes and how to recover.
Failure: Scheduled Task Does Not Run
- Cause: Incorrect task configuration, insufficient permissions, or missing script file.
- Recovery: Check task status and history:
Get-ScheduledTask -TaskName 'CPU Monitor' | Get-ScheduledTaskInfo | Format-List *
Ensure the script path is correct. If wrong, update the action:
Set-ScheduledTask -TaskName 'CPU Monitor' -Action (New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-File "C:\Monitoring\Check-CpuAlert.ps1"')
Also verify that the user account running the task has read and execute permissions on the script file. If the task runs as SYSTEM, ensure the script path is accessible by SYSTEM (it usually is).
Failure: Email Not Sent
- Cause: SMTP server unreachable, authentication required, or firewall block.
- Recovery: Test email manually:
Send-MailMessage -To '[email protected]' -From '[email protected]' -Subject 'Test' -Body 'Test' -SmtpServer 'smtp.example.com'
If it fails, check network connectivity and SMTP settings. Consider using a fallback like writing to a webhook or a file. Modern SMTP servers often require TLS and authentication, which Send-MailMessage does not support well. Use the Send-MailKitMessage cmdlet from the MailKit module for better support:
Install-Module -Name MailKit -Scope CurrentUser
$cred = Get-Credential
Send-MailKitMessage -From '[email protected]' -To '[email protected]' -Subject 'Test' -TextBody 'Test' -SmtpServer 'smtp.example.com' -Port 587 -UseSecureConnectionIfAvailable -Credential $cred
Alternatively, use a webhook as described earlier to bypass SMTP entirely.
Failure: False Alerts or Missed Alerts
- Cause: Threshold set too low or high, or metric retrieval error.
- Recovery: Review collected values over time. Adjust thresholds in the function. Verify the metric retrieval works independently:
Get-Counter '\Processor(_Total)\% Processor Time'
If the performance counter is missing, rebuild it with lodctr /r from an elevated command prompt. For missed alerts, ensure the scheduled task is running at the expected interval and that the script exits without errors. Add logging to capture exceptions.
Failure: Script Hangs or Uses High CPU
- Cause: A command waiting for input, an infinite loop, or a resource-intensive query.
- Recovery: Add timeouts to commands that may hang, e.g.,
Invoke-WebRequest -TimeoutSec 10. Monitor the script's own resource usage. If a script hangs, kill it and debug locally. Usetry/catchblocks to handle errors gracefully.
Rollback Plan
To remove monitoring, delete the scheduled task and the monitoring folder:
Unregister-ScheduledTask -TaskName 'CPU Monitor' -Confirm:$false
Remove-Item -Path 'C:\Monitoring' -Recurse -Force
This completely removes the components. If you have multiple scheduled tasks, list them with Get-ScheduledTask -TaskPath '\' | Where-Object TaskName -like 'Monitor' and unregister each.
Common Pitfalls and How to Avoid Them
When implementing PowerShell monitoring, several pitfalls can undermine reliability.
Pitfall 1: Alert Fatigue
Why it happens: Too many alerts with low thresholds generate noise, causing administrators to ignore or disable alerts.
How to avoid: Set thresholds based on baseline data, not guesses. Use severity levels and only alert on critical conditions. Consolidate multiple alerts into a single digest email rather than separate emails for each issue. For example, send a summary of all critical metrics once per hour instead of every 5 minutes.
Pitfall 2: Hard-Coded Values in Scripts
Why it happens: Quick scripting often leads to hard-coded email addresses, thresholds, and paths. When environments change, scripts break silently.
How to avoid: Use a configuration file (e.g., JSON or XML) to store settings. Your scripts read from the config. Here is an example:
{
"SmtpServer": "smtp.example.com",
"FromAddress": "[email protected]",
"ToAddresses": ["[email protected]", "[email protected]"],
"CpuThreshold": 80,
"MemoryFreePercentThreshold": 10,
"DiskFreeGBThreshold": 10
}
Load it in your script:
$config = Get-Content 'C:\Monitoring\config.json' | ConvertFrom-Json
$result = Get-CpuUsage -Threshold $config.CpuThreshold
Pitfall 3: Not Handling PowerShell Version Differences
Why it happens: Scripts written for Windows PowerShell 5.1 may use cmdlets or syntax not available in PowerShell 7, or vice versa. For example, Send-MailMessage exists in 5.1 but is deprecated in 7.
How to avoid: Test scripts in both versions if you have a mixed environment. Use #requires -Version at the top of scripts to enforce a minimum version. Prefer cmdlets available in both versions or provide compatibility shims.
Pitfall 4: Ignoring Security
Why it happens: Monitoring scripts often run with elevated privileges. If an attacker can modify the script, they can execute arbitrary code as SYSTEM.
How to avoid: Restrict write permissions on the monitoring folder to administrators only. Store credentials securely using the Windows Credential Manager or a secure vault, never in plain text. Use execution policy to restrict script execution. Regularly review scheduled tasks and scripts for unauthorized changes.
Pitfall 5: Monitoring the Monitoring System
Why it happens: People set up monitoring and forget about it. The monitoring scripts themselves can fail, and no one notices because the alerts stop.
How to avoid: Implement a heartbeat or watchdog. For example, have a separate scheduled task that checks if the monitoring task ran recently and alerts if not. Or use a service like Dead Man's Snitch (external) to alert when your monitoring has not checked in. Additionally, log script runs and review logs periodically.
Operations Checklist
Use this checklist for ongoing operations and reviews. Assign an owner for each task and set a review frequency.
| Task | Frequency | Owner | Description |
|---|---|---|---|
| Review alert history | Weekly | IT Operations Lead | Check logs and email sent items for alert frequency and false positives. Adjust thresholds if needed. |
| Verify scheduled tasks | Daily | Monitoring Administrator | Use Get-ScheduledTask to ensure monitoring tasks are enabled and have not failed. Check last run result is 0. |
| Test alert delivery | Monthly | IT Operations Lead | Send test alerts to confirm email or webhook channels are working. |
| Adjust thresholds | As needed | IT Operations Lead | Based on observed baseline metrics, fine-tune thresholds to reduce noise. |
| Update scripts | When environment changes | Monitoring Administrator | Modify monitoring scripts if new services or servers are added. |
| Backup monitoring scripts | Before changes | Monitoring Administrator | Copy script folder to a backup location (e.g., C:\MonitoringBackup). |
| Review security permissions | Quarterly | Security Administrator | Ensure only authorized users can modify monitoring scripts and scheduled tasks. |
Example: Reviewing Alert History
To show recent entries from the log file:
Get-Content 'C:\Monitoring\log.txt' -Tail 50
This displays the last 50 lines of the log for quick review.
If you are logging metrics to CSV, you can analyze trends:
Import-Csv 'C:\Monitoring\metrics.csv' | Where-Object Metric -eq 'CPU Usage (5s avg)' | Select-Object -Last 100
This gives the last 100 CPU readings for trend analysis.
Scaling to Multiple Machines
Once your single-machine monitoring works, you can extend it to multiple hosts using PowerShell Remoting. Enable remoting on target machines with Enable-PSRemoting -Force. Then, from the monitoring server, use Invoke-Command to run checks remotely:
$computers = @('Server1', 'Server2', 'Server3')
$results = Invoke-Command -ComputerName $computers -ScriptBlock {
. C:\Monitoring\Get-CpuUsage.ps1
Get-CpuUsage -Threshold 80
} -Credential $cred
$results | Where-Object Status -eq 'Critical' | Format-Table -AutoSize
This collects CPU usage from all servers in parallel. You can then aggregate results and send a single alert if any server exceeds the threshold. Remember to handle remoting errors, as some machines may be offline. Use -ErrorAction SilentlyContinue and check $? to detect failures.
For larger environments, consider using PowerShell Jobs or runspaces for concurrency, or a configuration management tool like Ansible or Desired State Configuration to deploy monitoring scripts consistently.
Conclusion
PowerShell provides a flexible and cost-effective way to monitor your Windows environment and set up custom alerts. By following this guide, you have learned how to:
- Inventory your environment and confirm prerequisites.
- Design a monitoring strategy with appropriate metrics and thresholds.
- Create a safe, scoped monitoring configuration using scripts and scheduled tasks.
- Implement CPU, memory, and disk monitors with alerting as templates for other metrics.
- Verify the monitoring works through diagnostic checks.
- Build a simple HTML dashboard for real-time visibility.
- Handle common failure modes and rollback cleanly.
- Avoid common pitfalls like alert fatigue and hard-coded values.
- Establish an operations checklist for ongoing maintenance.
- Scale to multiple machines with PowerShell Remoting.
As a next step, expand your monitoring to include event log analysis, service status, and custom application metrics. Use the same pattern to create additional checks and combine them into a single comprehensive monitoring script. Remember to start narrow and measurable, as a local pilot, before scaling to production. With these practical examples, you can build a reliable monitoring system tailored to your needs.