我只是在尝试一些基本的批处理编程。我在执行过程中遇到一些错误
set /a x=0
:while1
if %x% leq 5 (
echo %x%
goto:callfun
/dir:/Prod /user:admin /pass:anc /level:error >> C:\Logs\A.txt
set file=C:\Logs\J_FINANCIALS_EVENING.log
set /a "cnt=0"
for /f %%a in ('type "%file%"^|find "!Kitchen.Error.NoRepDefinied!" /i /c') do set /a cnt=%%a
if %cnt% NEQ 0 (
if %x% NEQ 5 (
DEL C:\Logs\abc.txt
)
set /a x=x+1
goto :while1
)
echo "OUTSIDE LOOP"
echo The Status is %errorlevel%
call:check_file
exit /b %errorlevel%
)
endlocal
callfun:
CALL C:\Pentaho\pdi-ce-5.2.0.0-209\data-integration\kitchen.bat /rep:"Admin" /job:"XXXX"
我在
收到错误设置/a "x = 0"
0此时出乎意料。
我在这里做错了什么?
最佳答案
每集约20亿的delayedexpansion
在 block 语句(括号中的一系列语句)
中,整个 block 被解析并然后执行。 block 中的任何 %var%
都将被该变量的值替换在 block 被解析时 - 在执行 block 之前 - 同样的事情适用于 FOR ... DO( block )
。
因此,IF (something) else (somethingelse)
将在 IF
时使用 %variables%
的值执行遇到了。
克服这个问题的两种常见方法是 1) 使用 setlocal enabledelayedexpansion
并使用 !var!
代替 %var%
来访问var
的更改值或 2) 调用子例程以使用更改后的值执行进一步处理。
因此 - 简单修复:
SETLOCAL ENABLEDELAYEDEXPANSION
set /a x=0
:while1
if %x% leq 5 (
echo !x!
goto callfun
REM this following line appear to make no sense in winbatch
/dir:/Prod /user:admin /pass:anc /level:error >> C:\Logs\A.txt
set "file=C:\Logs\J_FINANCIALS_EVENING.log"
set /a cnt=0
for /f %%a in ('type "%file%"^|find "!Kitchen.Error.NoRepDefinied!" /i /c') do set /a cnt=%%a
if !cnt! NEQ 0 (
if !x! NEQ 5 (
DEL C:\Logs\abc.txt
)
set /a x=x+1
goto while1
)
echo "OUTSIDE LOOP"
echo The Status is !errorlevel!
call :check_file
exit /b !errorlevel!
)
endlocal
REM Note that this will fall-through to the process. Best add
GOTO :EOF
REM Here.
REM Colon must precede label
:callfun
CALL C:\Pentaho\pdi-ce-5.2.0.0-209\data-integration\kitchen.bat /rep:"Admin" /job:"XXXX"
REM Note that this would exit the subroutine by reaching (apparent) EOF. Best add
GOTO :EOF
REM Here - as a habit - it contributes to preventing fall-through failures
REM if you add a new subroutine and forget to include the newly-required goto :eof
注意事项:
GOTO 不要求标签上有冒号except :EOF
的特殊情况定义为end文件的
SET/a 不需要引号。
SET "stringname=stringvalue"是字符串赋值的良好语法,因为引号导致行中的任何尾随空格不包含在赋值中。
在循环中变化的任何 %var%
都应该变成 !var!
并带有 delayedexpansion
以访问 运行时
而不是 parse-time
值。
(我只解决了延迟扩展错误 - 其他问题用 REM 标记)
关于Windows 批处理编程——此时出乎意料,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27064886/