简体   繁体   English

Windows XP上的/ f命令的问题

[英]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. 我正在使用Windows XP Service Pack 3,并且默认情况下在Windows注册表中启用了命令扩展。 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. 不知何故,以下命令在此版本的Windows上不起作用,但是如果我在Windows Server 2003或Windows Vista Business中运行它,则可以正常工作。 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. 问题在于,在Windows XP上,/ f选项似乎根本不起作用,并且命令的do部分从未执行过。

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. 提前致谢。

That's because tasklist.exe outputs to STDERR when no task is found. 这是因为没有找到任务时tasklist.exe输出到STDERR The for /f loop gets to see STDOUT only, so in case python.exe is not running, it has nothing to loop on. for /f循环只能看到STDOUT ,因此在python.exe没有运行的情况下,没有任何循环可以进行。

Redirecting STDERR into STDOUT ( 2>&1 ) works: STDERR重定向到STDOUT2>&1 )的工作原理是:

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. ^字符是为此工作所必需的转义序列。

The following does work on my Windows XP computer: 以下在我的Windows XP计算机上确实起作用:

@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 注意使用%%A
(Sorry, I used java.exe because no python.exe was running at the time of my test ;) ) (对不起,我使用java.exe是因为在测试时没有python.exe在运行;))

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
)

This will work and not display the 这将起作用,并且不会显示

INFO: No tasks running with the specified criteria INFO:没有任务以指定条件运行

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
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM