Killing Process as a Scheduled Task

A client of mine recently configured a Windows Scheduled Task to kill unwanted/hung process on a nightly basis.  One could argue the merits of these tasks, but I just need to “get things done”, so moving on…

The problem with these tasks is that they return error codes if the task in question is not actually running.  This generates errors in the OS, and I get paged as a result.  What is going on here?

Looking at the scheduled task, we see that it consists to a single executable… “taskkill.exe /f /im [process]”.  If the process is running, it gets terminated with no error code.  If it is not running, we get rc=80.

I figured we could do better a bit better, and an hour of bashing my head against the limitations of cmd.exe later, we have a script:

@echo off
REM killProc.bat – J. Greg Mackinnon, 2010-04-09
REM uses "taskkill.exe" to terminate the process specified by the first input argument
REM PROVIDES: the return code of the "taskkill" process, or "100" if a process name was not provided as input
REM REQUIRES: "tasklist.exe", "taskkill.exe", cmd.exe running under Windows 2000 or later.

set exitCode=0
set proc=%1
if NOT DEFINED proc goto error

tasklist.exe /FI "IMAGENAME eq %proc%" 2>NUL | find /I "%proc%" >NUL
taskkill /f /im %proc%
set exitCode=%errorlevel%

goto end

echo You must provide a valid process image name as an argument to this script.
set exitCode=100
goto end

exit /B %exitCode%

Now we just create a scheduled task with the following syntax:

cmd.exe /c killProc.bat [processName.exe]

If the process is running, we get the return code from “taskkill.exe”.  If the process is not running we get rc=0.  If no process name was specified, we get rc=100.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s