我不知道问题出在哪里。我有tool.exe
一个用于 grep、读取和写入注册表的程序。
它有errorlevel
代码0
,1
并且2
,根据该工具的语法,一切都是正确的:
"%tool_ROOT%\BIN\tool.exe" /g "%%A" %%B "%%C"`
并且工作正常,除非我将代码包装到for do (cmd)
例子:
:: %%A // is registry path
:: %%B // is parameter
:: %%C // is value*
@echo off
set logfile=log.LOG
for /F "tokens=1,2,3 delims=+" %%A in (CHECK.txt) do (
"%tool_ROOT%\BIN\tool.exe" /g "%%A" %%B "%%C"
@if "%errorlevel%" == "0" (
@ECHO %DATE% %TIME% ----- %%B WITH PARAMETER %%C ALREADY EXIST>>%logfile%
)
@if "%errorlevel%" == "1" (
@ECHO %DATE% %TIME% -----CURRENT VALUE OF %%B is>>%logfile%
)
@if "%errorlevel%" == "2" (
@ECHO %DATE% %TIME% -----%%B DOESN'T EXIST IN REGISTRY>>%logfile%
)
)
已经尝试过^
每次关门前)
答案1
@echo off && setlocal
set "logfile=.\log.log"
set "tool_cmd=.\bin\tool.exe"
cd /d "Path\To\Tool\Exec\Root\Folder"
for /f "tokens=1-3 delims=+" %%a in ('type "File_Check.txt" ^| find "+"
')do (call ) & "%tool_cmd%" /g "%%~a" %%~b "%%~c" & >>"%logfile%" (
if "%errorlevel%" == "0" (echo\ %date% %time% ----- %%b with parameter %%c already exist
)else if "%errorlevel%" == "1" (echo\ %date% %time% ----- current value of %%~b is
)else if "%errorlevel%" == "2" (echo\ %date% %time% ----- %%~b doesn't exist in registry
) )
timeout -1 | type "%logfile% & endlocal
1.定义变量时,请使用双引号,以防万一,或者像朋友说的那样,放心使用它们......
set "logfile=log.log"
2.设置可执行文件的完整路径,我没有在您的代码中看到它的定义,并且还设置了您的日志文件的完整路径......
set "logfile=D:\Path\To\log.log"
set "tool_cmd=D:\Path\To\Root\Tool\Folder\bin\tool.exe"
3.将您的文件提交给type
命令,并使用find
仅过滤带有分隔符的行+
...
for ...('type "File_Check.txt" ^| find "+" ')do ...
4.由于一切都指向与errorlevel
值相关的一些问题/行为,在使用执行命令之前...\tool.exe
,重置errorlevel
为0
,进行测试并查看结果,当然之后你可以删除...
...)do (call ) & "%tool_cmd%" /g "%%~a" %%~b "%%~c"...
观察:1请注意命令中有一个空格,这是必需的:
(callspace)
观察:2一个
if
接一个地if
执行echo string
,但如果实际上没有写入日志文件,则errorlevel
此返回的值将是什么?errorlevel
执行后值是否会改变echo string + redirector to file
?这些很容易出现特殊情况,我强烈建议进行测试并阅读下面文本中链接的答案以更好地理解...
Not only are there difference between commands, but a single command can behave differently depending on whether it was run from the command line, or within a batch script with a .bat extension, or from within a batch script with a .cmd extension
-@dbenham
5.在每个孤立的行上使用if condition() else if condition()...
而不是if condition()
,在下一行进行新的条件处理,即使它已经满足一个或多个前一行中定义的条件。
if "%errorlevel%" == "0" (
echo\ %date% %time% ----- %%b with parameter %%c already exist
) else if "%errorlevel%" == "1" (
echo\ %date% %time% ----- current value of %%~b is
) else if "%errorlevel%" == "2" (
echo\ %date% %time% ----- %%~b doesn't exist in registry
) else (
echo\ Look at this bro!
echo\ No previous one condition met as true!
echo\ What to do now?
echo\ But if it is not necessary/does not occur,
echo\ you can remove the last else
echo\ As i did in the answer code
)
6.至于重定向到您的日志文件,我建议执行if
块 [ >file-log (if ())
] 内的命令,并且已经重定向一次,无论if condition
或任何else if condition()
返回同一文件的内容......
"%tool_cmd%" /g "%%~a" %%~b "%%~c" & >>"%logfile%" (
if.. else if.. else if...
)
观察:请注意,在没有看到文件内容(字符串布局)的情况下,我提出的建议仅仅来自假设......