views:

919

answers:

4

Hello.

I'm using Windows XP Service Pack 3 and have Command Extensions enabled by default in the Windows Registry. Somehow, the following command does not work on this version of Windows but if I run it in Windows Server 2003 or Windows Vista Business, it works just fine. Any clue?

The problem is that on Windows XP, it seems like the /f option is not working at all and the do part of the command never gets executed.

This is the command:

for /f "tokens=1 delims=: " %A in ('tasklist /FI "IMAGENAME eq python.exe" /NH') do (
If "%A" == "python.exe" (
    echo "It's running"
) Else (
    echo "It's not running"
)
)

Thanks in advance.

+1  A: 

The following does work on my Windows XP computer:

@echo off
for /f "tokens=1 delims=: " %%A in ('tasklist /FI "IMAGENAME eq java.exe" /NH') do (
    If "%%A" == "java.exe" (
     echo "It's running"
    ) Else (
     echo "It's not running"
    )
)

Note the use of %%A
(Sorry, I used java.exe because no python.exe was running at the time of my test ;) )

VonC
+4  A: 

That's because tasklist.exe outputs to STDERR when no task is found. The for /f loop gets to see STDOUT only, so in case python.exe is not running, it has nothing to loop on.

Redirecting STDERR into STDOUT (2>&1) works:

for /F "tokens=1 delims=: " %A in ('tasklist /FI "IMAGENAME eq python.exe" /NH 2^>^&1') do (
  if "%A"=="python.exe" (
    echo "It's running"
  ) else (
    echo "It's not running"
  )
)

The ^ characters are escape sequences necessary for this to work.

Tomalak
Need to edit the %A to %%A if this is going to be in a batch file...
Patrick Cuff
I simply kept his original format. But, yes, that's what you'd have to do.
Tomalak
Also, this is case sensitive, so it will work for "python.exe" but not "Python.exe". Make the if statement "if /i %%A equ python.exe" to make it case insensitive.
Patrick Cuff
A: 

This will work and not display the

INFO: No tasks running with the specified criteria

message:

@echo off
set found=0

for /f "tokens=1 delims=: " %%A in ('tasklist /NH') do (
    If /i "%%A" equ "python.exe" (
        set found=1
    ) 
)

if %found%==1 (
    @echo It's running
) else (
    @echo It's not running
)
Patrick Cuff
The answer above that redirects STDERR is better.
Patrick Cuff
A: 
Set RUNNING=False
for /f "tokens=1 delims=: " %%a in ('tasklist /FI "IMAGENAME eq python.exe" /NH 2^>NUL') do (Set RUNNING=True)
If %RUNNING% == True (
    @Echo It IS running
) ELSE (
    @Echo It's NOT running
)
Daz