我有以下批处理文件:
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 已存在,如您所见 If 我回答 n 是否要选择另一个目录?变量 "%确认% 显示为 y。
有什么想法吗?
Windows 命令处理器在执行使用该命令块的命令之前,使用命令块中的语法%variable%
替换所有环境变量引用,该语法以(
开头,以匹配)
结尾。
这意味着在执行命令IF之前,%confirm%
在第一次运行批处理文件时被替换两次。在命令提示符窗口中运行批处理文件时,可以在不echo off
的情况下看到此行为,请参阅调试批处理文件。
一种解决方案是使用延迟扩展,如命令提示符窗口中set /?
IF和FOR上运行的命令SET输出的帮助所解释的那样。
但更好的做法是在不必要的地方避免使用命令块。
在这种情况下,对是/否提示符使用命令CHOICE也比set /P
更好。
@echo off
cd
goto Begin
:PromptUser
%SystemRoot%System32choice.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 /?
另请参阅:
- GOTO :EOF 回到哪里?
- Windows 命令解释器 (CMD.EXE( 如何解析脚本?
- 如何阻止Windows命令解释器在不正确的用户输入上退出批处理文件执行?