Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Batch file 提示的批处理文件异常行为_Batch File - Fatal编程技术网

Batch file 提示的批处理文件异常行为

Batch file 提示的批处理文件异常行为,batch-file,Batch File,我有以下批处理文件: 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%"=="

我有以下批处理文件:

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


有什么想法吗?

Windows命令处理器在执行使用命令块的命令之前,使用语法
%variable%
替换命令块中以
开始,以匹配的
结束)开头的所有环境变量引用

这意味着在执行命令之前,批处理文件的第一次运行时,如果执行了,则会将
%confirm%
替换为nothing两次。在命令提示窗口中运行批处理文件而不执行
echo off
时,可以看到此行为,请参阅

一种解决方案是,通过在命令提示符窗口中运行命令SEToutput,在IFFOR示例中使用

但更好的方法是避免在不必要的地方使用命令块。
在这种情况下,对是/否提示使用命令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/?
  • 如果/?
  • mkdir/?
  • rem/?
  • 设置/?
另见:


建议您使用
setlocal
%confirm%
作为
y
而不是
n
,脚本可能以前在同一CMD实例中执行。很好的解释。很好的详细信息。谢谢!