Checking if a folder exists using a .bat file

WindowsBatch File

Windows Problem Overview


I would like to be able to check if a certain folder (FolderA) exists and if so, for a message to be displayed and then the batch file to be exited.

If FolderA does not exist, I would then like to check if another folder (FolderB) exists. If FolderB does not exist, a message should be displayed and the folder should be created, and if FolderB does exist, a message should be displayed saying so.

Does anybody have any idea on the code I could simply use on notepad to create a batch file to allow me to do this?

All of this needs to be done in one .bat file.

Windows Solutions


Solution 1 - Windows

For a file:

if exist yourfilename (
  echo Yes 
) else (
  echo No
)

Replace yourfilename with the name of your file.

For a directory:

if exist yourfoldername\ (
  echo Yes 
) else (
  echo No
)

Replace yourfoldername with the name of your folder.

A trailing backslash (\) seems to be enough to distinguish between directories and ordinary files.

official documentation for if

Solution 2 - Windows

I think the answer is here (possibly duplicate):

https://stackoverflow.com/questions/138981/how-do-i-test-if-a-file-is-a-directory-in-a-batch-script

IF EXIST %VAR%\NUL ECHO It's a directory

Replace %VAR% with your directory. Please read the original answer because includes details about handling white spaces in the folder name.

As foxidrive said, this might not be reliable on NT class windows. It works for me, but I know it has some limitations (which you can find in the referenced question)

if exist "c:\folder\" echo folder exists 

should be enough for modern windows.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3179825View Question on Stackoverflow
Solution 1 - Windows09stephenbView Answer on Stackoverflow
Solution 2 - WindowsCosmin VanăView Answer on Stackoverflow