Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with for /f command on Windows XP

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 Answers

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.

like image 134
Tomalak Avatar answered Nov 30 '25 20:11

Tomalak