在for循环中丢失变量范围

时间:2016-05-17 20:24:20

标签: windows batch-file cmd

这应该按原样运作

set "status="
for /F "usebackq skip=1 tokens=3 delims=," %%H in (`schtasks.exe /fo csv /query /tn "\MS2\Import Process"`) do set "status=%%H"
set status=%status:"=%
echo The Import status: %status%

这表示状态为READY

我想每隔5秒检查一次状态1分钟:

for /l %%i in (1, 5, 300) do (
    set "status="
    for /F "usebackq skip=1 tokens=3 delims=," %%H in (`schtasks.exe /fo csv /query /tn "\MS2\Import Process"`) do set "status=%%H"
    set status=%status:"=%
    echo The Import status: %status%
    timeout /t 5
)

这表示状态始终为空

我正在使用%%的概念,因为我在批处理文件中运行它。

为什么在for循环中没有正确设置状态

编辑:尝试使用delayedexpansion

setlocal EnableDelayedExpansion

for /l %%i in (1, 5, 300) do (
    set "status="
    for /F "usebackq skip=1 tokens=3 delims=," %%H in (`schtasks.exe /fo csv /query /tn "\MS2\Import Process"`) do set "status=%%H"
    echo The Import status: !status!
    timeout /t 5
)

它仍然只是说状态为空。 我也在回声

之前得到ERROR: The system cannot find the file specified.

我尝试将set "status="放在for循环之外但没有用。

1 个答案:

答案 0 :(得分:1)

  • 删除"围绕双引号"使用%%~H
  • 使用schtasks
  • 跳过从if not defined status …输出中获取的尾随空白行
  • 修改Windows stores scheduled tasks as XML files。为了避免(有点混乱)消息ERROR: The system cannot find the file specified检查任务是否存在(从文件系统测试errorlevel)。

更新了代码段:

echo OFF
SETLOCAL EnableExtensions EnableDelayedExpansion
set "tasktocheck=\MS2\Import Process"

rem check scheduled task existence silently
>NUL 2>&1 schtasks.exe /fo csv /query /tn "%tasktocheck%"
if errorlevel 1 (
     echo "%tasktocheck%" scheduled task not found
     rem quit the script raising errorlevel 1
     exit /B 1
)
for /l %%i in (1, 5, 300) do (
    rem remove variable `status` (i.e. make it undefined) in next line
    set "status="
    for /F "usebackq skip=1 tokens=3 delims=," %%H in (
            `schtasks.exe /fo csv /query /tn "%tasktocheck%"`
        ) do if not defined status set "status=%%~H"
    rem      ^^^^^^^^^^^^^^^^^^^^^  skip trailing blank line taken from schtasks output
    rem Remove "surrounding double quotes"       ^  note the ~ tilde
    echo The Import status: !status!
    timeout /t 5
)

资源(必读):