Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

In more detail, I want to create a folder named VTS on the C:\ drive, but only if that folder doesn't already exist. I don't want to overwrite the contents of the folder if it already exists and the batch is executed.

like image 947
Bill Avatar asked Nov 12 '10 14:11

Bill


People also ask

What is %% in a batch file?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.

How do I create a batch file from a folder?

To create a Windows batch file, follow these steps: Open a text file, such as a Notepad or WordPad document. Add your commands, starting with @echo [off], followed by, each in a new line, title [title of your batch script], echo [first line], and pause. Save your file with the file extension BAT, for example, test.

What is the difference between md and mkdir?

The md and mkdir commands are functionally identical. You can also create new folders in Windows Explorer by going to File → New → Folder. You may indicate an absolute or relative path for the path parameter. When absolute, the new directory is created as specified from the root directory.


2 Answers

You just use this: if not exist "C:\VTS\" mkdir C:\VTS it wll create a directory only if the folder does not exist.

Note that this existence test will return true only if VTS exists and is a directory. If it is not there, or is there as a file, the mkdir command will run, and should cause an error. You might want to check for whether VTS exists as a file as well.

like image 98
The Answerer Avatar answered Oct 25 '22 08:10

The Answerer


if exist C:\VTS\NUL echo "Folder already exists"  if not exist C:\VTS\NUL echo "Folder does not exist" 

See also https://support.microsoft.com/en-us/kb/65994

(Update March 7, 2018; Microsoft article is down, archive on https://web.archive.org/web/20150609092521/https://support.microsoft.com/en-us/kb/65994 )

like image 32
Martin Schapendonk Avatar answered Oct 25 '22 07:10

Martin Schapendonk