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.
### Step-by-Step Explanation:
1. **Initialization**: The script sets up a few variables, including the log file path and the monitoring interval.
2. **Creating the Monitoring Function**: A function called `Monitor-Performance` is defined, which gathers CPU and memory usage statistics.
3. **Logging Data**: The gathered data is formatted and written to the specified log file.
4. **Continuous Monitoring**: The script enters a loop where it continuously logs performance statistics until the user decides to stop it.
5. **Error Handling**: Basic error handling ensures that if an issue occurs while gathering data, the script can report the error without stopping.
6. **Graceful Exit**: The script provides a method for the user to stop monitoring gracefully.
Start using this script today to monitor your system’s performance effectively!

# 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."
}

This script serves as a foundation that can be further enhanced with additional features, such as sending email alerts when CPU usage exceeds a certain threshold or integrating with external monitoring tools. Be sure to customize the log file path as necessary!