Reputation: 21
Does anyone know how to stop a process that is hung at around 45% CPU usage using powershell.
I run into having to do this alot manually and would like to:
First develop a script that can find the process by name (in this case it's a process called dfileman.exe used by an application running on a Windows 2003 server), check to see if it's stuck at equal to or greater than 45% CPU usage for more than 5 minutes and stop it if it meets the criteria. The application will start a new process the next time it needs it so I'm not worried about restarting it.
Second, use MS SCOM to monitor the dfileman.exe process, run the above script whenever it gets hung and send me an email whenever the script was run.
Any help would be greatly appreciated. Even if it's just helping me with the script.
What I have so far is:
$ProcessName = "defilman.exe"
$PSEmailServer = "smtp.company.com"
foreach ($proc in (Get-WmiObject Win32_Processor)){
if($proc.numberofcores -eq $null){
$cores++
}else{
$cores = $cores + $proc.numberofcores
}
}
$cpuusage = [Math]::round(((((Get-Counter "\Process($ProcessName)\% Processor Time" -MaxSamples 2).Countersamples)[0].CookedValue)/$cores),2)
if ($cpuusage -gt 45)
Send-MailMessage -To "Me (myaddress)" -From "Me (myaddress)" -Subject "DFileMan Process Hung" -body "An instance of $ProcessName on Server has reached a CPU Percentage of $cpuusage %. Please Kill Process Immediately"
else
Exit
Upvotes: 0
Views: 3022
Reputation: 36297
So an If statement is written like this: If(test){code to run if test passes} right now you are missing the { } from that. Corrected code:
if ($cpuusage -gt 45){
Send-MailMessage -To "Me (myaddress)" -From "Me (myaddress)" -Subject "DFileMan Process Hung" -body "An instance of $ProcessName on Server has reached a CPU Percentage of $cpuusage %. Please Kill Process Immediately"
}
Upvotes: 0
Reputation: 24071
Instead of a custom script, take a look at Performance Monitor. It has built-in functionality for taking actions when a counter stays long enough on specific a value.
After Perfmon has detected that the app is using too much CPU, you can use Powershell or whatever to kill the process.
Upvotes: 1