← script library

Automate System Performance Monitoring with PowerShell

Monitoring & HealthDecember 30, 2024

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.

powershell
# 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.

Ready when you are.

Try ServerEngine free for 7 days.