Ryan Killeen
Ryan Killeen

Reputation: 130

Poll Process CPU in Powershell over time

Very new to powershell, so here it goes.

So the end goal is: Every ten seconds, check if an IIS process is over a certain CPU usage. If it sustains above a certain level for more than a minute, reset it.

I understand that Get-Counter "\Process(w3wp)\% Processor Time" will give me the number I need.

How would I go about checking it every 10 seconds? The logic for comparing to previous checks I think I can manage.

Thanks!

Upvotes: 0

Views: 861

Answers (2)

TheMadTechnician
TheMadTechnician

Reputation: 36332

I'll contribute an answer. I will use a While loop as well, but formatted a bit differently.

$Countdown = 0
While((Get-Counter "\Process(w3wp)\% Processor Time"|sort -Descending |Select -First 1) -gt <target CPU usage>){
    $Countdown+=10
    if($countdown -gt 60){
        Reset IIS
        $Countdown = 0
    }
    start-sleep 10
}

Then schedule it to run once a minute, or every 5 minutes, or whatever. If it runs and something is over your target usage it will continue to run until it gets to a minute, then it does whatever you need to reset, and set $countdown back to 0. I put the sleep after the reset, so if the usage shoots right back up it will continue to run and will reset after a minute again.

Upvotes: 1

HAL9256
HAL9256

Reputation: 13483

You could have a script like this:

While (1){

#Checking Code
Get-Counter "\Process(w3wp)\% Processor Time"

#Sleep for 10 seconds
Sleep 10

}

Or the "better" option is to have a scheduled task that runs every minute or so.

Upvotes: 1

Related Questions