Windows command processor substitutes all environment variable references using syntax %variable%
within a command block starting with (
and ending with matching )
before executing the command which uses the command block.
This means here that %confirm%
is replaced twice by nothing on first run of the batch file before the command IF is executed at all. This behavior can be seen on running the batch file without echo off
from within a command prompt window, see debugging a batch file.
One solution is using delayed expansion as explained by the help of command SET output on running in a command prompt window set /?
on an IF and a FOR example.
But much better is avoiding command blocks where not really necessary.
In this case usage of command CHOICE for the yes/no prompt is also better than set /P
.
@echo off
cd \
goto Begin
:PromptUser
%SystemRoot%\System32\choice.exe /C YN /N /M "Do you want to choose another directory (Y/N)? "
if errorlevel 2 goto :EOF
:Begin
set "UserInputPath="
set /P "UserInputPath=What Directory would you like to make? "
rem Has the user not input any string?
if not defined UserInputPath goto Begin
rem Remove all double quotes from user path.
set "UserInputPath=%UserInputPath:"=%"
rem Is there no string left anymore?
if not defined UserInputPath goto Begin
rem Does the directory already exist?
if exist "%UserInputPath%" goto PromptUser
rem Create the directory and verify if that was really successful.
rem Otherwise the entered string was invalid for a folder path or
rem the user does not have the necessary permissions to create it.
rem An error message is output by command MKDIR on an error.
mkdir "%UserInputPath%"
if errorlevel 1 goto Begin
rem Other commands executed after creation of the directory.
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.
cd /?
choice /?
echo /?
goto /?
if /?
mkdir /?
rem /?
set /?
See also: