Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inside a batch file, how can I tell whether a process is running?

I'd like to write a batch file that checks to see if a process is running, and takes one action if it is, and another action if it isn't.

I know I can use tasklist to list all running processes, but is there a simpler way to directly check on a specific process?

It seems like this should work, but it doesn't:

tasklist /fi "imagename eq firefox.exe" /hn | MyTask
IF %MyTask%=="" GOTO DO_NOTHING
'do something here
:DO_NOTHING

Using the solution provided by atzz, here is a complete working demo:

Edit: Simplified, and modified to work under both WinXP and Vista

echo off

set process_1="firefox.exe"
set process_2="iexplore.exe"
set ignore_result=INFO:

for /f "usebackq" %%A in (`tasklist /nh /fi "imagename eq %process_1%"`) do if not %%A==%ignore_result% Exit
for /f "usebackq" %%B in (`tasklist /nh /fi "imagename eq %process_2%"`) do if not %%B==%ignore_result% Exit

start "C:\Program Files\Internet Explorer\iexplore.exe" www.google.com
like image 918
JosephStyons Avatar asked Nov 19 '08 17:11

JosephStyons


People also ask

How do you check a process is running or not in CMD?

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.

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.

What is an easy way to understand the use of IF in batch files?

The easiest way to understand the IF statement that batch files use, is to imagine that every decision results in either 1 or 0. When 1 is the result, that's the same as TRUE or YES, so we do whatever comes next.

How do I see what processes are running on Windows 10 command line?

Just tap on Start, type cmd.exe and open the Command Prompt from the results to get started. Simply typing tasklist and hitting the Enter-key displays a list of all running processes on the system. Each process is listed with its name, process ID, session name and number, and memory usage.


2 Answers

You can use "for /f" construct to analyze program output.

set running=0
for /f "usebackq" %%T in (`tasklist /nh /fi "imagename eq firefox.exe"`) do set running=1

Also, it's a good idea to stick a

setlocal EnableExtensions

at the begginning of your script, just in case if the user has it disabled by default.

like image 188
atzz Avatar answered Oct 03 '22 20:10

atzz


Some options:

  • PsList from Microsoft

http://www.windowsdevcenter.com/pub/a/oreilly/windows/news/win2kcommands_0401.html#ps

  • Cygwin (for ps)
  • the resource kit (for ps.vbs)

http://www.windowsdevcenter.com/pub/a/oreilly/windows/news/win2kcommands_0401.html#ps

  • Powershell for get-process.
like image 28
Lou Franco Avatar answered Oct 03 '22 18:10

Lou Franco