PowerShell Script to Check CPU Usage Easily
Get-Counter '\Processor(_Total)\% Processor Time' in PowerShell to check current CPU usage percentage.Examples
How to Think About It
Algorithm
Code
try { $cpu = Get-Counter '\Processor(_Total)\% Processor Time' $usage = $cpu.CounterSamples.CookedValue Write-Output "CPU Usage: {0:N2} %" -f $usage } catch { Write-Output "Failed to get CPU usage." }
Dry Run
Let's trace running the script on a system with 12.34% CPU usage.
Get CPU counter
Get-Counter returns an object with CPU usage data, e.g., 12.34
Extract usage value
Extracted value is 12.34 from the counter samples
Format and output
Formatted string 'CPU Usage: 12.34 %' is printed
| Step | Action | Value |
|---|---|---|
| 1 | Get-Counter '\Processor(_Total)\% Processor Time' | 12.34 |
| 2 | Extract CookedValue | 12.34 |
| 3 | Output formatted string | CPU Usage: 12.34 % |
Why This Works
Step 1: Get-Counter fetches CPU data
The Get-Counter cmdlet queries Windows performance counters, here specifically the total CPU usage.
Step 2: Extract the numeric value
The CPU usage percentage is inside CounterSamples.CookedValue, which is a number representing usage.
Step 3: Format output for readability
Using -f formats the number to two decimals and adds a percent sign for clear display.
Alternative Approaches
try { $cpuLoad = Get-WmiObject Win32_Processor | Measure-Object -Property LoadPercentage -Average | Select-Object -ExpandProperty Average Write-Output "CPU Usage: $cpuLoad %" } catch { Write-Output "Failed to get CPU usage via WMI." }
Add-Type -AssemblyName System.Diagnostics $cpuCounter = New-Object System.Diagnostics.PerformanceCounter('Processor', '% Processor Time', '_Total') Start-Sleep -Seconds 1 $usage = $cpuCounter.NextValue() Write-Output "CPU Usage: {0:N2} %" -f $usage
Complexity: O(1) time, O(1) space
Time Complexity
The script performs a single system query without loops, so it runs in constant time.
Space Complexity
It uses a fixed amount of memory to store the counter data and output string.
Which Approach is Fastest?
Using Get-Counter is fast and real-time, WMI is simpler but slower, and .NET class method requires a delay but offers flexibility.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Get-Counter | O(1) | O(1) | Real-time CPU usage with built-in cmdlet |
| WMI | O(1) | O(1) | Simple average CPU load, less real-time |
| .NET PerformanceCounter | O(1) + delay | O(1) | Custom .NET usage with more control |