我有以下批处理文件:
echo off
CD \
:Begin
set /p UserInputPath= "What Directory would you like to make?"
if not exist C:\%UserInputPath% (
mkdir %UserInputPath%
) else (
set /p confirm= "Do you want choose another directory?"
echo %confirm%
if "%confirm%"=="y" goto Begin
)
输出:
C:\>echo off
What Directory would you like to make?ff
Do you want choose another directory?n
y
What Directory would you like to make?
查看输出,目录ff已经存在,如您所见,如果 我回答n是否要选择另一个目录?变量 “%confirm%显示为y。
有什么想法吗?
答案 0 :(得分:1)
在执行使用命令块的命令之前,Windows命令处理器在命令块中使用语法%variable%
替换所有环境变量引用,该语法以(
开头并以匹配的)
结尾。
这意味着%confirm%
在第一次运行批处理文件之前被两次替换为{strong> IF 。可以在命令提示符窗口中运行没有echo off
的批处理文件时看到此行为,请参见debugging a batch file。
一种解决方案是使用delayed expansion,如在 IF 上的命令提示符窗口set /?
中运行命令 SET 所帮助和 FOR 示例。
更好的是避免在不必要的地方使用命令块。
在这种情况下,将命令 CHOICE 用于是/否提示也比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.
要了解所使用的命令及其工作方式,请打开命令提示符窗口,在其中执行以下命令,并非常仔细地阅读每个命令显示的所有帮助页面。
cd /?
choice /?
echo /?
goto /?
if /?
mkdir /?
rem /?
set /?
另请参阅: