问题描述
我有需要在一个32位的上下文中运行的批处理文件,以便包含一个位$ C $的c调用它自己的路径的32位命令处理器。此脚本还需要能够在失败时,它通过不会返回错误code出口/ B 123
。但是...结果
当退出
是在(
)
块,和包括之后的任何声明,这不能正确返回。
I have a batch file that needs to be run in a 32-bit context so contains a bit of code to call the 32-bit command processor with its own path. This script also needs to be able to return error code on failure which it does via exit /b 123
. However...
When the exit
is in a (
)
block, AND contains any statement after it, this does not get returned correctly.
@echo off
setlocal EnableDelayedExpansion
rem Ensure we're running in 32-bit mode
if not %PROCESSOR_ARCHITECTURE%==x86 (
echo Thunking to 32-bit mode
%Windir%\SysWOW64\cmd.exe /c %0
echo !ERRORLEVEL!
exit /b !ERRORLEVEL!
)
(
echo before
exit /b 456
echo after
)
的输出如下所示:
The output is as follows:
H:\>sub.bat
Thunking to 32-bit mode
before
0
H:\>
如果您删除回声
的退出
,那么它的工作原理完全如预期。在
If you remove the echo
after the exit
, then it works exactly as expected.
H:\>sub.bat
Thunking to 32-bit mode
before
456
H:\>
即使你用 REM
或其它任何命令替换回声
,它仍然失败。如果您手动运行32位的cmd.exe
并运行相同的脚本,退出code被设置正确。
Even if you replace the echo
with a rem
or any other command, it still fails. If you manually run the 32-bit cmd.exe
and run the same script, the exit code gets set correctly.
H:\>sub.bat
before
H:\>echo %ERRORLEVEL%
456
H:\>
谁能给这个解释和解决方法?
Can anyone give an explanation and a workaround for this?
推荐答案
使用在脚本中的其他部分/ b开关的原因造成的出口code通过CMD的第二个实例会丢失.exe文件。
The use of the /b switch in the "else" part of the script is causing the exit code to be lost by the second instance of cmd.exe.
在批处理文件的第二个实例从SYSWOW64执行时,它会用456其母公司CMD.EXE的code退出将收到此退出code,但在$ P $没有兴趣pserving它。该CMD.EXE能够成功运行批处理,从而以0退出,回到第一个实例。
When the second instance of the batch file is executed from Syswow64, it will be exiting with the code of 456. Its parent cmd.exe will receive this exit code but has no interest in preserving it. The cmd.exe was able to successfully run the batch and thus exits with 0, back to the first instance.
如果你省略了脚本的其他人的一部分/ b开关,这迫使该批处理文件退出其父CMD.EXE,而不只是完成处理。由于CMD.EXE是那么的告知与出口456 code 的退出,这将是preserved。
If you omit the /b switch in the "else" part of the script, this forces the batch file to quit its parent cmd.exe, rather than just finish processing. As the cmd.exe is then told to quit with the 456 exit code, this will be preserved.
有关退出帮助文本做推断这种行为,但它似乎并不十分明显,直到你记住这个阅读!
The help text for "exit" does infer this behaviour, but it doesn't seem very obvious until you read it with this in mind!
这篇关于退出/ B不与其他命令块内正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!