Inside a batch file, how can I tell whether a process is running?
Solution 1
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.
Solution 2
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.
JosephStyons
I started out as a professional developer using Delphi and Oracle in a Win32 client-server environment for a manufacturing company. I worked for five years in consulting, implementing solutions for dozens of clients and using many disparate technologies. Since then, I've worked for and with the non-profit industry, building applications that help them move their missions forward. My bread-and-butter is VB.NET and C# against a SQL Server back-end using a SOA architecture. But I can and will use whatever tool gets the job done, and I've had fun doing so with Angular, jQuery, ASP.NET, PHP, and even my own homemade frameworks to deliver solutions against that platform.
Updated on July 10, 2022Comments
-
JosephStyons almost 2 years
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