How to stop a process automatically using a script package

How to check if a process is running from a batch / cmd file? And if the process is running, how can I stop the process automatically?

Like a cmd script thingy, can someone give me some tips or help me make this kind of script.

Example (pseudo code):

If calc.exe is running Stop calc.exe 

I need 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 
+6
source share
3 answers

First, you have the wrong command to stop the process, for example calc.exe.NET STOP will stop the service, but not the normal program process. Instead, you want TASKKILL.

The second one. If you know you want to kill a process, if it exists, then why do you think you need to check if it is executed first before you kill it? You can simply try to kill the process independently. If it does not exist, an error is generated and no harm is done. If it exists, then it will be killed with a successful message.

 taskkill /im calc.exe 

If you do not want to see the error message, redirect stderr to nul using 2>nul . If you also do not want to see a success message, then redirect stdout to nul using >nul .

 taskkill /im calc.exe >nul 2>nul 

If you want to take action depending on the result, you can use 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 can use ERRORLEVEL to determine what to do based on the result.

+13
source

A more readable and simpler command is something like this:

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

This technique never returns an error code if the process is not running when the / IM switch will return an error if the process is not running. You can also use wild cards, for example:

taskkill / F / FI "IMAGENAME eq calc * .exe" to kill any process starting with "calc" and ending with ".exe" in the name.

+3
source

Check the tasklist command - this command gives you a list of running tasks and services. Check if the job you are interested in is being done using regex

Then use the taskkill command to kill the service or task.

0
source

Source: https://habr.com/ru/post/949347/


All Articles