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.

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.