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:
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.
if NOT DEFINED proc goto error
tasklist.exe /FI "IMAGENAME eq %proc%" 2>NUL | find /I "%proc%" >NUL
if %ERRORLEVEL% EQU 0 (
taskkill /f /im %proc%
echo You must provide a valid process image name as an argument to this script.
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.