Monitor System Performance with PowerShell

This PowerShell script monitors system performance by checking CPU and memory usage, providing an overview of resource consumption and potential bottlenecks.
Step 1: Retrieve System Performance Data
In this initial step, we will gather the current CPU and memory usage data using built-in PowerShell commands.

$cpuUsage = Get-WmiObject -Class Win32_Processor | Measure-Object -Property LoadPercentage -Average | Select-Object -ExpandProperty Average
$memInfo = Get-WmiObject -Class Win32_OperatingSystem
$totalMemory = $memInfo.TotalVisibleMemorySize
$freeMemory = $memInfo.FreePhysicalMemory
$usedMemory = $totalMemory – ($freeMemory * 1MB)
$memoryUsagePercentage = [math]::round(($usedMemory / $totalMemory) * 100, 2)

Step 2: Format and Display Performance Data
Now that we have gathered the performance data, we will format it for better readability and display the results to the user.

$performanceReport = @{
‘CPU Usage (%)’ = $cpuUsage
‘Used Memory (MB)’ = [math]::round($usedMemory / 1MB, 2)
‘Free Memory (MB)’ = [math]::round($freeMemory / 1MB, 2)
‘Memory Usage (%)’ = $memoryUsagePercentage
}
$performanceReport.GetEnumerator() | ForEach-Object {
Write-Host “$($_.Key): $($_.Value)”
}

Step 3: Log Performance Data to a File
To keep track of performance metrics over time, we will log this data to a text file. This can be beneficial for future analysis.

$logFilePath = “C:\Path\To\Your\PerformanceLog.txt”
$dateTime = Get-Date -Format “yyyy-MM-dd HH:mm:ss”
$logEntry = “$dateTime – CPU Usage: $cpuUsage%, Memory Usage: $memoryUsagePercentage%”
Add-Content -Path $logFilePath -Value $logEntry

Step 4: Set Up a User-Friendly Notification
Finally, we will set up a user-friendly notification to alert users about the current system performance, especially if the performance metrics are high.

if ($cpuUsage -gt 80 -or $memoryUsagePercentage -gt 80) {
[System.Windows.MessageBox]::Show(“ALERT: High System Resource Usage! Review performance metrics.”, “Performance Notification”, 0, [System.Windows.MessageBoxIcon]::Warning)
}

Step 5: Schedule the Script (Optional)
To continuously monitor system performance, you can schedule this script to run at set intervals using Windows Task Scheduler. This allows for real-time monitoring without manual intervention.

# This step typically involves using Task Scheduler within Windows, so no specific PowerShell code is provided here.