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

15,990

Solution 1

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.

Solution 2

Try taskkill /fi "IMAGENAME eq notepad.exe" Not finding notepad.exe will only throw an info instead of an error.

Share:
15,990
Mowgli
Author by

Mowgli

Do you have or know good programming/Tip and trick blog or website. Submit it to my collection here http://goo.gl/U9Bs4 View sites submitted so far here http://goo.gl/EV93J Submit & View Excel Formulas: http://goo.gl/P664R I am an Electrical Engineer. I enjoy programming a lot. I am not expert at programming but with Google search and reading, I can make it work and be become expert. I have programmed in many languages only one I haven't tired is Python.

Updated on September 15, 2022

Comments

  • Mowgli
    Mowgli about 1 year

    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.

  • joojaa
    joojaa over 10 years
    Possibly the asker was looking for taskkill /im notepad.exe || exit /b
  • Mowgli
    Mowgli over 10 years
    won't it throw error? if it does it may not execute next statements?
  • David Heffernan
    David Heffernan over 10 years
    It reports an error. And I show how to suppress that. But it will carry on executing the next statement. Remember this is batch we are talking about, not a real programming language! ;-)
  • David Heffernan
    David Heffernan over 10 years
    @joojaa Judging by the comments, it looks like that is not the case
  • Mowgli
    Mowgli over 10 years
    Thanks lol I you got me confused when you said real programming language.
  • David Heffernan
    David Heffernan over 10 years
    +1 That's quite nice. Avoids needing to reset error level. However, your final statement is misleading. Errors don't stop execution. Execution just plugs on in the face of errors.
  • Shaya
    Shaya over 4 years
    On Windows 10, Adding 2> nul to the taskkill command creates a "nul" file I'm unable to delete, only by rm nul. Any way to bypass this? Thanks.