Create folder with batch but only if it doesn't already exist

前端 未结 9 1691
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-12 09:03

Can anybody tell me how to do the following in in a Windows batch script? (*.bat):

  • Create a folder only if it doesn\'t already exist
相关标签:
9条回答
  • 2020-12-12 09:56

    I use this way, you should put a backslash at the end of the directory name to avoid that place exists in a file without extension with the same name as the directory you specified, never use "C:\VTS" because it can a file exists with the name "VTS" saved in "C:" partition, the correct way is to use "C:\VTS\", check out the backslash after the VTS, so is the right way.

    @echo off
    @break off
    @title Create folder with batch but only if it doesn't already exist - D3F4ULT
    @color 0a
    @cls
    
    setlocal EnableDelayedExpansion
    
    if not exist "C:\VTS\" (
      mkdir "C:\VTS\"
      if "!errorlevel!" EQU "0" (
        echo Folder created successfully
      ) else (
        echo Error while creating folder
      )
    ) else (
      echo Folder already exists
    )
    
    pause
    exit
    
    0 讨论(0)
  • 2020-12-12 09:56

    You can use:

    if not exist "C:\VTS\" mkdir "C:\VTS"
    

    You can also expand the code to replace any missing expected files.

    if not exist "C:\VTS\important.file" echo. > "C:\VTS\important.file"
    
    0 讨论(0)
  • 2020-12-12 09:57

    Just call mkdir C:\VTS no matter what. It will simply report that the subdirectory already exists.

    Edit: As others have noted, this does set the %ERRORLEVEL% if the folder already exists. If your batch (or any processes calling it) doesn't care about the error level, this method works nicely. Since the question made no mention of avoiding the error level, this answer is perfectly valid. It fulfills the needs of creating the folder if it doesn't exist, and it doesn't overwrite the contents of an existing folder. Otherwise follow Martin Schapendonk's answer.

    0 讨论(0)
提交回复
热议问题