9

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.

tomdemuyt
  • 4,572
  • 2
  • 31
  • 60
Mowgli
  • 3,422
  • 21
  • 64
  • 88

2 Answers2

12

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.

Community
  • 1
  • 1
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • Possibly the asker was looking for **taskkill /im notepad.exe || exit /b** – joojaa Apr 09 '13 at 13:26
  • won't it throw error? if it does it may not execute next statements? – Mowgli Apr 09 '13 at 13:27
  • 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 Apr 09 '13 at 13:27
  • @joojaa Judging by the comments, it looks like that is not the case – David Heffernan Apr 09 '13 at 13:28
  • 1
    Thanks lol I you got me confused when you said real programming language. – Mowgli Apr 09 '13 at 13:31
  • 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. – Shaya Mar 11 '19 at 19:06
7

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

tomdemuyt
  • 4,572
  • 2
  • 31
  • 60
  • +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. – David Heffernan Apr 09 '13 at 13:45