How can I check if an application is running from a batch (well cmd) file?
I need to not launch another instance if a program is already running. (I can\'t change th
Another possibility I came up with, inspired by using grep, is:
tasklist /FI "IMAGENAME eq myapp.exe" 2>NUL | find /I /N "myapp.exe">NUL
if "%ERRORLEVEL%"=="0" echo Program is running
It doesn't need to save an extra file, so I prefer this method.
Under Windows you can use Windows Management Instrumentation (WMI) to ensure that no apps with the specified command line is launched, for example:
wmic process where (name="nmake.exe") get commandline | findstr /i /c:"/f load.mak" /c:"/f build.mak" > NUL && (echo THE BUILD HAS BEEN STARTED ALREADY! > %ALREADY_STARTED% & exit /b 1)
TASKLIST | FINDSTR ProgramName || START "" "Path\ProgramName.exe"
The answer provided by Matt Lacey works for Windows XP. However, in Windows Server 2003 the line
tasklist /FI "IMAGENAME eq notepad.exe" /FO CSV > search.log
returns
INFO: No tasks are running which match the specified criteria.
which is then read as the process is running.
I don't have a heap of batch scripting experience, so my soulution is to then search for the process name in the search.log
file and pump the results into another file and search that for any output.
tasklist /FI "IMAGENAME eq notepad.exe" /FO CSV > search.log
FINDSTR notepad.exe search.log > found.log
FOR /F %%A IN (found.log) DO IF %%~zA EQU 0 GOTO end
start notepad.exe
:end
del search.log
del found.log
I hope this helps someone else.
Here's how I've worked it out:
tasklist /FI "IMAGENAME eq notepad.exe" /FO CSV > search.log
FOR /F %%A IN (search.log) DO IF %%~zA EQU 0 GOTO end
start notepad.exe
:end
del search.log
The above will open Notepad if it is not already running.
Edit: Note that this won't find applications hidden from the tasklist. This will include any scheduled tasks running as a different user, as these are automatically hidden.
I use PV.exe from http://www.teamcti.com/pview/prcview.htm installed in Program Files\PV with a batch file like this:
@echo off
PATH=%PATH%;%PROGRAMFILES%\PV;%PROGRAMFILES%\YourProgram
PV.EXE YourProgram.exe >nul
if ERRORLEVEL 1 goto Process_NotFound
:Process_Found
echo YourProgram is running
goto END
:Process_NotFound
echo YourProgram is not running
YourProgram.exe
goto END
:END