@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "Directory=mydir\subdir 1\subdir 2"
md "%Directory%" 2>nul
if not exist "%Directory%\*" (
echo Failed to create directory "%Directory%"
pause
goto :EOF
)
rem Other commands after successful creation of the directory.
endlocal
重要的是目录路径现在以 \* 结束或至少使用反斜杠 . 否则,示例可能是在目录 mydir\subdir 1 中存在名为 subdir 2 的文件,其中使用条件 if not exist "%Directory%" 将评估为false,尽管没有目录 subdir 2 .
当然也可以先进行目录检查,然后创建目录(如果尚未存在) .
@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "Directory=mydir\subdir 1\subdir 2"
if not exist "%Directory%\*" (
md "%Directory%"
if errorlevel 1 (
pause
goto :EOF
)
)
rem Other commands after successful creation of the directory.
endlocal
如果无法创建目录结构,用户现在可以看到命令 MD 输出的错误消息,简要说明原因 .
使用operator || 可以更紧凑地编写此批处理代码:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "Directory=mydir\subdir 1\subdir 2"
if not exist "%Directory%\*" md "%Directory%" || pause & goto :EOF
rem Other commands after successful creation of the directory.
endlocal
2 回答
创建目录结构的标准方法是:
默认情况下,启用命令扩展并禁用延迟扩展 . 上面的批处理代码显式设置了这个环境 .
命令 MD 使用已启用的命令扩展名创建指定目录的完整目录结构 .
如果目录已存在, MD 将输出错误 . 这可能有助于通知用户手动输入命令输入目录路径中可能存在的错误,因为用户可能想要创建新目录并且错误地输入了现有目录的名称 .
但是对于命令 MD 的脚本使用,如果要创建的目录已存在,则此命令通常会输出错误消息 . 如果命令 MD 有一个选项,在目录创建已存在并且退出时返回代码0,则输出错误消息将非常有用 . 但是没有这样的选择 .
上面的解决方案创建目录并抑制可能输出错误消息,并将其从句柄 STDERR 重定向到设备 NUL .
但由于目录路径中的字符无效,驱动器不可用(使用完整路径),目录的创建可能会失败,路径中的任何地方都有一个名称为指定目录的文件,NTFS权限不允许创建目录等
所以建议验证目录是否真的存在,这是通过以下方式完成的:
重要的是目录路径现在以
\*
结束或至少使用反斜杠 . 否则,示例可能是在目录mydir\subdir 1
中存在名为subdir 2
的文件,其中使用条件if not exist "%Directory%"
将评估为false,尽管没有目录subdir 2
.当然也可以先进行目录检查,然后创建目录(如果尚未存在) .
如果无法创建目录结构,用户现在可以看到命令 MD 输出的错误消息,简要说明原因 .
使用operator
||
可以更紧凑地编写此批处理代码:有关运算符
||
和&
的详细信息,请阅读Single line with multiple commands using Windows batch file上的答案 .在goto :EOF之前未使用命令 ENDLOCAL ,因为此命令还需要启用命令扩展 . Windows命令解释程序在执行批处理文件时执行此命令 .
要了解使用的命令及其工作方式,请打开命令提示符窗口,执行以下命令,并完全阅读为每个命令显示的所有帮助页面 .
echo /?
endlocal /?
goto /?
if /?
md /?
pause /?
set /?
setlocal /?
另请阅读有关Using Command Redirection Operators的Microsoft文章 .
您需要检查路径并创建它是否不存在
或者您也可以重定向stderr
您不需要先运行
mkdir mydir
,因为何时启用命令扩展
https://ss64.com/nt/md.html