If Notepad.exe is running then taskkill if not running go to next statement

Mowgli picture Mowgli · Apr 9, 2013 · Viewed 15.1k times · Source

I need help writing batch code.

In the initial state of my batch script I need to check if notepad.exe is running if it is running then
taskkill /im notepad.exe elsif notepad.exe is not running then go to next batch statement/code.

Answer

David Heffernan picture David Heffernan · Apr 9, 2013

You can simply execute taskkill /im notepad.exe in all cases. If it's not running, then taskill will having nothing to kill and will just return.

In that situation, taskkill will report an error and set the error level. You can suppress the reporting of the error by redirecting standard error:

taskkill /im notepad.exe 2> nul

As for the error level, you can just ignore that and it will be cleared by the next command that you execute. Or if needed, you can clear it yourself.

This approach is, in my view, better than trying to anticipate whether or not taskkill will succeed. You won't be able to anticipate all possible failure modes and since taskkill itself performs the very check that you are asking about, I think you may as well leave that check to taskkill.