Wednesday, September 9, 2009

powershell script to kill process by name that's been running for more than x minutes

If you ever have some badly written program that you have to use that leaves orphaned processes running in memory and you need to end them - but only the older ones then use this script. You only have change the name of the process and the number of minutes that it has to have been running for. (Note: It's a negative number from the current time).

##############################################
#
# Powershell script to kill off orphaned processes
# Free for any Use
#
# Script is not 'signed' so you either have to digitally sign it
# or run 'Set-ExecutionPolicy remotesigned' or 'Set-ExecutionPolicy
# Unrestricted' from Powershell at least once prior to using this script.
#
# Batch File syntax: powershell "& 'c:\foldername\killorphanproc.ps1'"
#
# To figure out the process name you can go into powershell and just
# run get-process by itself for a listing
#
# Script is provided 'As-Is' with no support.
#
##############################################


#Get list of processes matching the name and older than x minutes.
$orphanProcs = get-process | where {($_.Name -eq "winword") -and '
($_.StartTime -lt (get-date).addminutes(-30))}

#Check if list is Null and if not kill them all:
If ($orphanProcs) {
#display list
$orphanProcs
#kill list
$orphanProcs | foreach { $_.Kill() }
} Else {
echo "no processes found older than specified"
}

3 comments:

Anonymous said...

Thanks! Very handy! I just had to remove the single quote after the -and

$orphanProcs = get-process | where {($_.Name -eq "winword") -and
($_.StartTime -lt (get-date).addminutes(-30))}

Anonymous said...

Thanks! This helped me kill some orphaned processes.

Anonymous said...

This is VERY helpful. I tried writing something like this myself, but your version is much more elegant. Thanks a million!

-->S.