How to stop a process automatically via a batch script

cmd, process

Solution

First off, you have the wrong command to stop a process like calc.exe. NET STOP will stop a service, but not a normal program process. You want TASKKILL instead.

Second - If you know you want to kill the process if it exists, then why do you think you have to check if it is running first before you kill it? You can simply attempt to kill the process regardless. If it doesn't exist, then an error is generated, and no harm done. If it does exist, then it is killed with a success message.

taskkill /im calc.exe

If you don't want to see the error message, then redirect stderr to nul using `2>nul`. If you don't want to see the success message either, then redirect stdout to nul using `>nul`.

taskkill /im calc.exe >nul 2>nul

If you want to take action depending on the outcome, then you can use the conditional `&&` and `||` operators for success and failure.

taskkill /im calc.exe >nul 2>nul && (
  echo calc.exe was killed
) || (
  echo no process was killed
)

Or you could use the ERRORLEVEL to determine what to do depending on the outcome.

Problem

How can I check if a process is running from a batch/cmd file? And If process is running, how do I stop the process automatically? Like a cmd script thingy, can someone give me some hints or help me make that kind of script. Example (pseudo code): ``` If calc.exe is running Stop calc.exe ``` I want something like this: ``` @echo off :x PATH=C:\Windows\System32\calc.exe If calc.exe is ON goto Process_Stop :Process_Stop net stop calc.exe goto x ```

Original source