这工作,因为它应该
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 …
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 )
资源 (必读):
%%~H
等特殊页面) 命令行参数(参数) >>
, 2>&1
等特殊页面) 重定向