0

I have this code in my .bat file:

@echo off
setlocal enableextensions disabledelayedexpansion

//Run sqlcmd command to backup file

//error handler for sqlcmd
if %ERRORLEVEL% == 0(
    FOR /F "delims=|" %%I IN ('DIR /s "D:\Temp\*.bak" /b /O:D') DO set latestFile=%%I
    echo %latestFile%
) else (
    echo Error occured.
)

Problem

The result that I always got from echo %latestFile% is always ECHO is off meaning, the %%I is empty. However, when I move the for loop to outside of the if-else clause and used goto to execute the for loop, this problem does not occur.

1

1 Answer 1

1

By default, the CMD parser reads and parses an entire statement block inside parentheses before executing it. This means all variable expansion in the entire block happens before any commands are run. Here is a deeper explanation why this works this way.

To get around this, CMD supports Delayed Expansion, which allows variables to be re-parsed before each line in a statement block. The syntax for this is !variable!.

First, you need to enable delayed expansion, by changing your setlocal line from disabledelayedexpansion to enabledelayedexpansion. Second, you need to change your echo line to use ! instead of %

REM @echo off
setlocal enableextensions enabledelayedexpansion

//Run sqlcmd command to backup file

//error handler for sqlcmd
if %ERRORLEVEL% == 0(
    FOR /F "delims=|" %%I IN ('DIR /s "D:\Temp\*.bak" /b /O:D') DO set latestFile=%%I
    echo !latestFile!
) else (
    echo Error occured.
)

Finally, note that @echo off suppresses debugging information, and you should always remove or comment that line while debugging. It often makes the difference between having to guess which line failed and knowing.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.