How to check if a process is running via a batch script

后端 未结 18 2087
一个人的身影
一个人的身影 2020-11-22 07:38

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

相关标签:
18条回答
  • 2020-11-22 07:57

    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.

    0 讨论(0)
  • 2020-11-22 07:59

    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)

    0 讨论(0)
  • 2020-11-22 08:03
    TASKLIST | FINDSTR ProgramName || START "" "Path\ProgramName.exe"
    
    0 讨论(0)
  • 2020-11-22 08:04

    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.

    0 讨论(0)
  • 2020-11-22 08:05

    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.

    0 讨论(0)
  • 2020-11-22 08:06

    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
    
    0 讨论(0)
提交回复
热议问题