Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop a process automatically via a batch script

Tags:

process

cmd

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
like image 473
user2578034 Avatar asked Jul 12 '13 22:07

user2578034


2 Answers

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.

like image 96
dbenham Avatar answered Oct 20 '22 11:10

dbenham


A more readable and simpler command is something like this:

taskkill /F /FI "IMAGENAME eq calc.exe"

This methodology never returns an error code if the process isn't running where the /IM switch WILL return an error if the process is not running. You can also use wild cards like:

taskkill /F /FI "IMAGENAME eq calc*.exe" to kill any process that starts with 'calc' and ends with '.exe' in the name.

like image 34
outbred Avatar answered Oct 20 '22 10:10

outbred