Batch program to to check if process exists

前端 未结 5 1988
一整个雨季
一整个雨季 2020-12-02 14:55

I want a batch program, which will check if the process notepad.exe exists.

if notepad.exe exists, it will end the process

5条回答
  •  隐瞒了意图╮
    2020-12-02 15:20

    TASKLIST doesn't set an exit code that you could check in a batch file. One workaround to checking the exit code could be parsing its standard output (which you are presently redirecting to NUL). Apparently, if the process is found, TASKLIST will display its details, which include the image name too. Therefore, you could just use FIND or FINDSTR to check if the TASKLIST's output contains the name you have specified in the request. Both FIND and FINDSTR set a non-null exit code if the search was unsuccessful. So, this would work:

    @echo off
    tasklist /fi "imagename eq notepad.exe" | find /i "notepad.exe" > nul
    if not errorlevel 1 (taskkill /f /im "notepad.exe") else (
      specific commands to perform if the process was not found
    )
    exit
    

    There's also an alternative that doesn't involve TASKLIST at all. Unlike TASKLIST, TASKKILL does set an exit code. In particular, if it couldn't terminate a process because it simply didn't exist, it would set the exit code of 128. You could check for that code to perform your specific actions that you might need to perform in case the specified process didn't exist:

    @echo off
    taskkill /f /im "notepad.exe" > nul
    if errorlevel 128 (
      specific commands to perform if the process
      was not terminated because it was not found
    )
    exit
    

提交回复
热议问题