Every environment variable referenced with %VariableName%
within a command block starting with (
and ending with matching )
is expanded during preprocessing of entire command block by Windows command interpreter before executing the command which finally executes the already preprocessed command block.
This means %INPUT%
is replaced by the value of environment variable INPUT
before command FOR is executed at all. The environment variable INPUT
is not defined in the batch file above command FOR and so the comparisons in the command block depend on existence of this environment variable and its current value on starting the batch file.
Run in a command prompt window set /?
and read the help output into the console window. The usage of delayed environment variable expansion is explained by the help on an IF and a FOR example on which command blocks are used usually.
But there is a better solution for this task then enabling delayed expansion. Instead of using set /P INPUT=[Y/N]:
the command CHOICE is used which exits with an exit code assigned to ERRORLEVEL
depending on key pressed by the user. In this case ERRORLEVEL
is 1
if the user presses Y
or y
as being the first specified option or 2
if N
or n
is pressed by the user. Other values are not possible.
See also Microsoft support article Testing for a Specific Error Level in Batch Files explaining how ERRORLEVEL
can be evaluated in a batch file even within a command block without usage of delayed expansion.
cd /D "%INSTALLDIR%"
for /F %%I in ('dir /AD /B /O:-N 2^>nul') do (
%SystemRoot%\System32\choice.exe /C YN /N /M "Generate an answer file for %%I [Y/N]? "
if errorlevel 2 (echo Skipping %%I) else call :GetOptions "%%I"
)
goto :EOF
:GetOptions
cd /D "%~1"
set APPNAME=<"%~1.options"
for /F "usebackq" %%J in ("%~1.options") do set "OPTIONS=%%J"
echo %APPNAME%
echo %OPTIONS%
goto :EOF
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /?
cd /?
choice /?
dir /?
echo /?
for /?
goto /?
if /?
set /?
Read also the Microsoft article about Using Command Redirection Operators for an explanation of <
and 2>nul
. The redirection operator >
must be escaped with caret character ^
on FOR command line to be interpreted as literal character when Windows command interpreter processes this line before executing command FOR which executes the embedded dir
command line with using a separate command process started in background.
See also Where does GOTO :EOF return to?