title: powershell stop process using 45% cpu
body: <p>Does anyone know how to stop a process that is hung at around 45% CPU usage using powershell. </p>
  
  <p>I run into having to do this alot manually and would like to: </p>
  
  <p>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.  </p>
  
  <p>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.</p>
  
  <p>Any help would be greatly appreciated.  Even if it's just helping me with the script.</p>
  
  <p>What I have so far is:</p>
  
  <pre><code>$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
  </code></pre>