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
.