We got the requirement to monitor the performance for few minutes before starting the activity (CPU usage of a computer in last x minute ) in the PRODUCTION server and requested this to be automate instead of getting in to the server each time. The below same we have implemented in the our build Tool to make it automatic.
How to achieve?
We can achieve the above scenario by using the Get-Counter cmdlet in Powershell. It will gets performance counter data directly from the performance monitoring instrumentation in the Windows family of operating systems. Get-Counter gets performance data from a local computer or remote computers.
STEP 1: This below line will check the CPU usage of last 5 times with 1 second intervals. as shown below.
Get-counter -Counter “\Processor(_Total)\% Processor Time” -SampleInterval 1 -MaxSamples 5
STEP 2: Selecting the Counter Samples and calculating the Average of the CPU Usage.
select -ExpandProperty countersamples | select -ExpandProperty cookedvalue | Measure-Object -Average).average
Full Code
The following script will return the average CPU % over a period of 5 seconds with 5 samples averaged. The $_.CookedValue
is a variable for the current object in the pipeline.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<span style="color: #000000;">###################################################################################</span> #Project : How to Gets CPU performance counter data from local and remote computers. #Developer : Thiyagu S (dotnet-helpers.com) #Tools : PowerShell 5.1.15063.1155 #E-Mail : mail2thiyaguji@gmail.com ################################################################################### #-SampleInterval: parameter to increase the interval between continuous samples, #If the SampleInterval parameter isn't specified, Get-Counter uses a one-second interval. #-MaxSamples : Specifies the number of samples to get from each specified performance counter #If the MaxSamples parameter isn't specified, Get-Counter only gets one sample for each specified counter. $CPUAveragePerformance = (GET-COUNTER -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 2 -MaxSamples 5 |select -ExpandProperty countersamples | select -ExpandProperty cookedvalue | Measure-Object -Average).average Write-Host "Average of CPU usage (calculated with 5 Sample with interval of 2 sec) :" $CPUAveragePerformance |
OUTPUT:
What do you think?
I hope you have an idea of How to Get average CPU usage of a computer in last x minute with Powershell. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.