首页 文章

在批处理脚本中创建文件夹并忽略它是否存在

提问于
浏览
2

如何在批处理脚本中创建文件夹(和任何子文件夹)?重要的是,如果文件夹(或任何子文件夹)已经存在,则不应返回错误 .

例如,像这样:

  • mkdir mydir - 成功(现在已创建目录)

  • mkdir mydir\subdir - 成功(现在 mydir 包含 subdir

  • mkdir mydir - 成功(文件夹已存在,应该 not 抛出错误)

  • mkdir mydir\subdir - 成功(文件夹已存在,应该 not 抛出错误)

我真正需要的只是确保文件夹结构存在 .

2 回答

  • 6

    创建目录结构的标准方法是:

    @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
    

    默认情况下,启用命令扩展并禁用延迟扩展 . 上面的批处理代码显式设置了这个环境 .

    命令 MD 使用已启用的命令扩展名创建指定目录的完整目录结构 .

    如果目录已存在, MD 将输出错误 . 这可能有助于通知用户手动输入命令输入目录路径中可能存在的错误,因为用户可能想要创建新目录并且错误地输入了现有目录的名称 .

    但是对于命令 MD 的脚本使用,如果要创建的目录已存在,则此命令通常会输出错误消息 . 如果命令 MD 有一个选项,在目录创建已存在并且退出时返回代码0,则输出错误消息将非常有用 . 但是没有这样的选择 .

    上面的解决方案创建目录并抑制可能输出错误消息,并将其从句柄 STDERR 重定向到设备 NUL .

    但由于目录路径中的字符无效,驱动器不可用(使用完整路径),目录的创建可能会失败,路径中的任何地方都有一个名称为指定目录的文件,NTFS权限不允许创建目录等

    所以建议验证目录是否真的存在,这是通过以下方式完成的:

    if not exist "%Directory%\*"
    

    重要的是目录路径现在以 \* 结束或至少使用反斜杠 . 否则,示例可能是在目录 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
    

    有关运算符 ||& 的详细信息,请阅读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文章 .

  • 9

    您需要检查路径并创建它是否不存在

    if not exist mydir\subdir md mydir\subdir
    

    或者您也可以重定向stderr

    md mydir\subdir 2>NUL
    

    您不需要先运行 mkdir mydir ,因为

    MD会根据需要在路径中创建任何中间目录 .

    何时启用命令扩展

    https://ss64.com/nt/md.html

相关问题