2

I am trying to just see if an application is currently running based on the Image Name in the task manager or tasklist... I am using firefox.exe as the example but it always fails. The goal is to not launch another script if its already running and/or to taskkill it when we need.

This is my current status script:

@echo off
set STATUS=
FOR /F "tokens=*" %%A IN ('tasklist ^| findstr "firefox.exe"') DO SET STATUS=%%A
echo %STATUS%
if [%STATUS%]==[] set STATUS=stopped

echo %STATUS%

Always gives the following output: (it always fails on the if statement)

firefox.exe                   6216 Console                    1    411,760 K
6216 was unexpected at this time.

Do you have an idea why this is or suggest another way to go about achieve this?

Stainedart
  • 1,929
  • 4
  • 32
  • 53

4 Answers4

2

better than compare is the test of existence:

  if not defined status set "status=stopped"
Endoro
  • 37,015
  • 8
  • 50
  • 63
1

Try this instead:

if "%STATUS%"=="" set STATUS=stopped

The issue is that STATUS has spaces in it, and it's handled by the quotes but not brackets. Try the batch file below to see what's going on... right before the if statement, you will see the value of status which is echoed.

@echo off
set STATUS=
FOR /F "tokens=*" %%A IN ('tasklist ^| findstr "firefox.exe"') DO (
  SET STATUS=%%A
)
echo The status is "%STATUS%"
if [%STATUS%]==[] set STATUS=stopped

echo %STATUS%

See also this related thread: What is the proper way to test if variable is empty in a batch file?

Community
  • 1
  • 1
JohnD
  • 14,327
  • 4
  • 40
  • 53
1

Here's one method:

@echo off
set "prog=firefox.exe"
tasklist /fi "IMAGENAME EQ %prog%"| find /i "%prog%" >nul && (echo %prog% is running) || (echo %prog% is stopped)
foxidrive
  • 40,353
  • 10
  • 53
  • 68
1

The best way i have seen (for me) was this, which was from another user here on stack, can't find the original question though :

:LOOP
tasklist | find /i "program.exe" >nul 2>&1
IF ERRORLEVEL 1 (
  GOTO CONTINUE
) ELSE (
  ECHO Program still running!
  Timeout /T 3 /Nobreak
  GOTO LOOP
)

:CONTINUE

You can adjust the time you want (this one checks every 3 seconds)

Mark Wragg
  • 22,105
  • 7
  • 39
  • 68
Rakha
  • 1,874
  • 3
  • 26
  • 60