Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch program to to check if process exists

I want a batch program, which will check if the process notepad.exe exists.

if notepad.exe exists, it will end the process,

else the batch program will close itself.

Here is what I've done:

@echo off tasklist /fi "imagename eq notepad.exe" > nul if errorlevel 1 taskkill /f /im "notepad.exe" exit 

But it doesn't work. What is the wrong in my code?

like image 412
user2176930 Avatar asked Mar 16 '13 12:03

user2176930


People also ask

How can I tell if a process is running in CMD?

First of all open the Start Screen and type Cmd utility in search box then click on the search button. Click on the cmd utility icon; it opens a command-line window. Type Tasklist in it and press the enter key. This command shows all the running processes in your system.

How do you see if a process is running in Windows?

Hold Ctrl+Shift+Esc or right-click on the Windows bar, and choose Start Task Manager. In Windows Task Manager, click on More details. The Processes tab displays all running processes and their current resources usage.

What does tasklist command do?

Tasklist is a tool that displays a list of the processes that are running on either a local or remote machine.


1 Answers

TASKLIST does not set errorlevel.

echo off tasklist /fi "imagename eq notepad.exe" |find ":" > nul if errorlevel 1 taskkill /f /im "notepad.exe" exit 

should do the job, since ":" should appear in TASKLIST output only if the task is NOT found, hence FIND will set the errorlevel to 0 for not found and 1 for found

Nevertheless,

taskkill /f /im "notepad.exe"

will kill a notepad task if it exists - it can do nothing if no notepad task exists, so you don't really need to test - unless there's something else you want to do...like perhaps

echo off tasklist /fi "imagename eq notepad.exe" |find ":" > nul if errorlevel 1 taskkill /f /im "notepad.exe"&exit 

which would appear to do as you ask - kill the notepad process if it exists, then exit - otherwise continue with the batch

like image 91
Magoo Avatar answered Sep 22 '22 23:09

Magoo