To get CPU usage in PowerShell, you can use the Get-Counter cmdlet to retrieve the performance counter data related to CPU usage.
The following example shows how you can do it.
# Get CPU usage counter $cpuCounter = Get-Counter -Counter "\Processor(_Total)\% Processor Time" # Display CPU usage Write-Host "CPU Usage (%):" $cpuCounter.CounterSamples.CookedValue
Output:
In this script, the Get-Counter gets performance counter data, it retrieves the percentages of processor time for all CPUs and stores the result in the $cpuCounter variable.
The $cpuCounter.CounterSamples.CookedValue extracts the value of the CPU usage and displays it as a percentage.
After running the script, it displays the CPU usage on your system to the terminal.
You can also use the following PowerShell script to get CPU usage in percentage.
Get-CimInstance -ClassName win32_processor | Measure-Object -Property LoadPercentage -Average
Output:
PS C:\> Get-CimInstance -ClassName win32_processor | Measure-Object -Property LoadPercentage -Average
Count : 1
Average : 11
Sum :
Maximum :
Minimum :
Property : LoadPercentage
In this script, the Get-CimInstance retrieves information about the available processes using the Win32_processor class.
We then use the Measure-Object cmdlet to measure the average value of the LoadPercentage property. The -Average parameter returns the calculated average CPU usage percentage across all processors.
Conclusion
I hope the above article on getting CPU usage using PowerShell is helpful to you.
You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.