Can you see any reason why this would display 0
"%ConnectDirectExe%" -f"%ConnectDirectCredentials%" < "%CurrentCDConfigFile%" > "%CurrentCDTaskLogFile%"
ECHO %errorlevel%
yet this displays blank?
"%ConnectDirectExe%" -f"%ConnectDirectCredentials%" < "%CurrentCDConfigFile%" > "%CurrentCDTaskLogFile%"
SET Result=%errorlevel%
ECHO errorlevel is %Result%
Note that the “%ConnectDirectExe%” line in both cases exactly matches. If I invert the blocks to run in the opposite order, the results are similarly inverted, too.
Why can’t I store the result of %errorlevel% in Result and display it? It keeps on appearing as blank.
Update:
it seems like my SET statements aren’t being executed if they occur within the IF Block.
Given the following batch file, if.bat:
echo off
SET Result=1
ECHO ResultCaption1=%Result%
IF 1 equ 1 (
SET Result=2
ECHO ResultCaption2=%Result%
) else (
ECHO 1 is not = 2
)
When I run it, i see this output:
C:\Batch>if.bat
C:\Batch>echo off
ResultCaption1=1
ResultCaption2=1
C:\Batch>
Shouldn’t the second ECHO display
ResultCaption2=2
?
I suspect your code is embedded within a parenthesised block, perhaps as part of an IF statement or a FOR loop. The problem with that is the expansion occurs when the line is parsed, and the entire block is parsed at once, before anything in the block is executed. So
%errorlevel%will be the value before your command was executed, and%Result%will probably be undefined.The solution is to use delayed expansion, which must be enabled before it can be used. Type
HELP SETfrom the command prompt to get more info about delayed expansion and how it can help when dealing with blocks of code.