Batch program to to check if process exists Batch program to to check if process exists windows windows

Batch program to to check if process exists


TASKLIST does not set errorlevel.

echo offtasklist /fi "imagename eq notepad.exe" |find ":" > nulif errorlevel 1 taskkill /f /im "notepad.exe"exit

should do the job, since ":" should appear in TASKLIST output only if the task is NOT found, hence FIND will set the errorlevel to 0 for not found and 1 for found

Nevertheless,

taskkill /f /im "notepad.exe"

will kill a notepad task if it exists - it can do nothing if no notepad task exists, so you don't really need to test - unless there's something else you want to do...like perhaps

echo offtasklist /fi "imagename eq notepad.exe" |find ":" > nulif errorlevel 1 taskkill /f /im "notepad.exe"&exit

which would appear to do as you ask - kill the notepad process if it exists, then exit - otherwise continue with the batch


This is a one line solution.

It will run taskkill only if the process is really running otherwise it will just info that it is not running.

tasklist | find /i "notepad.exe" && taskkill /im notepad.exe /F || echo process "notepad.exe" not running.

This is the output in case the process was running:

notepad.exe           1960 Console                   0    112,260 KSUCCESS: The process "notepad.exe" with PID 1960 has been terminated.

This is the output in case not running:

process "notepad.exe" not running.


TASKLIST doesn't set an exit code that you could check in a batch file. One workaround to checking the exit code could be parsing its standard output (which you are presently redirecting to NUL). Apparently, if the process is found, TASKLIST will display its details, which include the image name too. Therefore, you could just use FIND or FINDSTR to check if the TASKLIST's output contains the name you have specified in the request. Both FIND and FINDSTR set a non-null exit code if the search was unsuccessful. So, this would work:

@echo offtasklist /fi "imagename eq notepad.exe" | find /i "notepad.exe" > nulif not errorlevel 1 (taskkill /f /im "notepad.exe") else (  specific commands to perform if the process was not found)exit

There's also an alternative that doesn't involve TASKLIST at all. Unlike TASKLIST, TASKKILL does set an exit code. In particular, if it couldn't terminate a process because it simply didn't exist, it would set the exit code of 128. You could check for that code to perform your specific actions that you might need to perform in case the specified process didn't exist:

@echo offtaskkill /f /im "notepad.exe" > nulif errorlevel 128 (  specific commands to perform if the process  was not terminated because it was not found)exit