在for循环中丢失variables作用域

这工作,因为它应该

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 ) 

这说明状态总是空的

我正在使用%%概念,因为我在batch file中运行它。

为什么在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. 就在回声之前

我尝试在for循环之外放置set "status=" ,但无济于事。

  • 删除“周围的双引号”使用%%~H
  • if not defined status …跳过从schtasks输出中获取的尾随空行if not defined status …
  • 编辑 : Windows将计划的任务存储为XML文件 。 为了避免(有点混淆)消息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` (ie 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 ) 

资源 (必读):

  • (命令参考) Windows CMD命令行的AZ索引
  • (有用的特殊性) Windows CMD Shell命令行语法
  • %%~H等特殊页面) 命令行参数(参数)
  • (特殊页面) EnableDelayedExpansion
  • >>2>&1等特殊页面) 重定向