Automate System Performance Monitoring with PowerShell
In this PowerShell script, we will create a professional tool to automate system performance monitoring. This script will track CPU and memory usage, logging the information to a text file at regular intervals. This solution is ideal for system administrators looking to keep track of performance metrics for troubleshooting or optimization purposes. The script sets up a few variables, including the log file path and the monitoring interval. A function called Monitor-Performance is defined, which gathers CPU and memory usage statistics. The gathered data is formatted and written to the specified log file, and the script enters a loop where it continuously logs performance statistics until the user decides to stop it. Basic error handling ensures that if an issue occurs while gathering data, the script can report the error without stopping.
# Define the log file and monitoring interval
$logFile = "C:\PerformanceLog.txt"
$monitorInterval = 5 # in seconds
# Create the monitoring function
function Monitor-Performance {
try {
# Gather CPU and Memory Usage
$cpuUsage = Get-Counter '\Processor(_Total)\% Processor Time'
$memoryUsage = Get-Counter '\Memory\Available MBytes'
# Format the output
$formattedOutput = "$(Get-Date) - CPU Usage: $($cpuUsage.CounterSamples.CookedValue)% - Available Memory: $($memoryUsage.CounterSamples.CookedValue)MB"
# Log the output to the file
Add-Content -Path $logFile -Value $formattedOutput
} catch {
Write-Host "ERROR: Unable to gather performance data."
Write-Error $_
}
}
# Infinite loop to continuously monitor
try {
Write-Host "Starting performance monitoring... Press Ctrl+C to stop."
while ($true) {
Monitor-Performance
Start-Sleep -Seconds $monitorInterval
}
} catch {
Write-Host "Monitoring stopped by user."
}Run it across your fleet
This script runs as-is on a single host. Paste it into ServerEngine to schedule it, run it on a whole server group in parallel, and keep the credentials out of the file — see the scripts documentation and the credential store.
More in Monitoring & Health
Disk Space Cleanup and Report Script
2025-01-14User Account Status Reporting Script
2025-01-13Automated Disk Space Monitoring Script
2025-01-13Monitor System Performance with PowerShell
2025-01-12Automating System Health Check with PowerShell
2025-01-05Enhancing System Monitoring with PowerShell: Real-time Log Management
2024-12-29Ready when you are.
Try ServerEngine free for 7 days.