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

后端 未结 18 2257
一个人的身影
一个人的身影 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:55

    I needed a solution with a retry. This code will run until the process is found and then kill it. You can set a timeout or anything if you like.

    Notes:

    • The ".exe" is mandatory
    • You could make a file runnable with parameters, version below
        :: Set programm you want to kill
        :: Fileextension is mandatory
        SET KillProg=explorer.exe
    
        :: Set waiting time between 2 requests in seconds
        SET /A "_wait=3"
    
        :ProcessNotFound
            tasklist /NH /FI "IMAGENAME eq %KillProg%" | FIND /I "%KillProg%"
            IF "%ERRORLEVEL%"=="0" (
                TASKKILL.EXE /F /T /IM %KillProg%
            ) ELSE (
                timeout /t %_wait%
                GOTO :ProcessNotFound
            )
    

    taskkill.bat:

        :: Get program name from argumentlist
        IF NOT "%~1"=="" (
            SET "KillProg=%~1"
        ) ELSE (
            ECHO Usage: "%~nx0" ProgramToKill.exe & EXIT /B
        )
    
        :: Set waiting time between 2 requests in seconds
        SET /A "_wait=3"
    
        :ProcessNotFound
            tasklist /NH /FI "IMAGENAME eq %KillProg%" | FIND /I "%KillProg%"
            IF "%ERRORLEVEL%"=="0" (
                TASKKILL.EXE /F /T /IM %KillProg%
            ) ELSE (
                timeout /t %_wait%
                GOTO :ProcessNotFound
            )
    

    Run with .\taskkill.bat ProgramToKill.exe

提交回复
热议问题