Você precisa Expansão atrasada se quiser usar uma variável que você alterou no mesmo bloco de comando. (Um bloco de comandos é uma série de comandos entre parênteses ( e ) .) Variáveis atrasadas são referenciadas usando !var! em vez de %var% .
Exemplo :
@ECHO OFF
SETLOCAL EnableExtensions EnableDelayedExpansion
cmd /C exit /B 99
echo before ^(command block^) %%errorlevel%%=%errorlevel% ^^!errorlevel^^!=!errorlevel!
(
(call)
echo ^(inside command block^) %%errorlevel%%=%errorlevel% ^^!errorlevel^^!=!errorlevel!
(call )
echo ^(inside command block^) %%errorlevel%%=%errorlevel% ^^!errorlevel^^!=!errorlevel!
)
echo after ^(command block^) %%errorlevel%%=%errorlevel% ^^!errorlevel^^!=!errorlevel!
Saída :
==> D:\bat\SU13027.bat
before (command block) %errorlevel%=99 !errorlevel!=99
(inside command block) %errorlevel%=99 !errorlevel!=1
(inside command block) %errorlevel%=99 !errorlevel!=0
after (command block) %errorlevel%=0 !errorlevel!=0
Os truques (call) e (call ) foram roubados de essa resposta de Dbenham para definir ERRORLEVEL como 0 pergunta:
If you want to force the
errorlevelto0, then you can use this totally non-intuitive, but very effective syntax:(call ). The space after call is critical. If you want to set theerrorlevelto1, you can use(call). It is critical that there not be any space after call.