Windows if exists folder

How to verify if a file exists in a batch file?

I have to create a .BAT file that does this:

  1. If C:\myprogram\sync\data.handler exists, exit;
  2. If C:\myprogram\html\data.sql does not exist, exit;
  3. In C:\myprogram\sync\ delete all files and folders except ( test , test3 and test2 )
  4. Copy C:\myprogram\html\data.sql to C:\myprogram\sync\
  5. Call other batch file with option sync.bat myprogram.ini .

If it was in the Bash environment it was easy for me, but I do not know how to test if a file or folder exists and if it is a file or folder.

3 Answers 3

You can use IF EXIST to check for a file:

If you do not need an «else», you can do something like this:

Here’s a working example of searching for a file or a folder:

Type IF /? to get help about if, it clearly explains how to use IF EXIST.

To delete a complete tree except some folders, see the answer of this question: Windows batch script to delete everything in a folder except one

Finally copying just means calling COPY and calling another bat file can be done like this:

Here is a good example on how to do a command if a file does or does not exist:

We will take those three files and put it in a temporary place. After deleting the folder, it will restore those three files.

Use the XCOPY command:

I will explain what the /c /d /h /e /i /y means:

Call other batch file with option sync.bat myprogram.ini.

I am not sure what you mean by this, but if you just want to open both of these files you just put the path of the file like

If it was in the Bash environment it was easy for me, but I do not know how to test if a file or folder exists and if it is a file or folder.

You are using a batch file. You mentioned earlier you have to create a .bat file to use this:

I have to create a .BAT file that does this:

Create folder in batch script and ignore if it exists

How do I create folder(and any subfolders) in batch script? What is important, if folder(or any subfolders) already exists, it should not return error.

For example, something like this:

  • mkdir mydir — success(directory is now created)
  • mkdir mydir\subdir — success(now mydir contains subdir )
  • mkdir mydir — success(folder already exists, should not throw an error)
  • mkdir mydir\subdir — success(folders already exists, should not throw an error)

What I actually need is just to ensure that folders structure exists.

2 Answers 2

A standard method to create a directory structure is:

By default command extensions are enabled and delayed expansion is disabled. The batch code above explicitly sets up this environment.

The command MD creates the complete directory structure to specified directory with enabled command extensions.

MD outputs an error if the directory already exists. This might be useful to inform a user entering the command manually about a possible mistake in entered directory path as it could be that the user wanted to create a new directory and has entered just by mistake the name of an already existing directory.

But for scripted usage of command MD it is often a problem that this command outputs an error message if the directory to create already exists. It would be really helpful if command MD would have an option to not output an error message in case of directory to create already existing and exiting with return code 0 in this case. But there is no such option.

The solution above creates the directory and suppresses a perhaps output error message with redirecting it from handle STDERR to device NUL.

Читайте также:  Принтеры лазерные samsung ml 1210 для windows

But the creation of the directory could fail because of invalid character in directory path, drive not available (on using full path), there is anywhere in path a file with name of a specified directory, NTFS permissions don’t permit creation of the directory, etc.

So it is advisable to verify if the directory really exists which is done with:

It is important that the directory path ends now with \* or at least with a backslash. Otherwise it could be possible for the example that there is a file with name subdir 2 in directory mydir\subdir 1 which on usage of the condition if not exist «%Directory%» would evaluate to false although there is no directory subdir 2 .

It is of course also possible to do the directory check first and create the directory if not already existing.

The user can see now the error message output by command MD if the directory structure could not be created explaining briefly the reason.

This batch code could be written more compact using operator || :

For details about the operators || and & read the answer on Single line with multiple commands using Windows batch file.

The command ENDLOCAL is not used before goto :EOF because this command requires also enabled command extensions. Windows command interpreter executes this command implicit on leaving execution of the batch file.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

Read also the Microsoft article about Using Command Redirection Operators.

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.

9 Answers 9

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.

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.

Check whether a file/folder exists, with cmd command-line (NOT batch script)

I am on the windows console trying to find out whether a file/folder exists or not.

EXIST could be used in batch, but it is not available on the command-line:

5 Answers 5

The solution when the resource is a file it is pretty straight-forward as indicated by others:

Unfortunately, the above does not work for directories. The EXIST function returns the same result for both missing and present folders. Fortunately, there is an obscure workaround:

It turns out that to support constructs like appending >NUL on command statements, there is a sort of virtual file named «NUL» in every directory. Checking for its existence is equivalent to a check for the directory’s existence.

This behavior is documented in a Microsoft knowledge base article ( https://support.microsoft.com/en-us/kb/65994 ) and I have confirmed its behavior on FreeDOS 1.1 and in a Windows 7 command shell.

Читайте также:  Самый лучший активатор windows 10 без ключа

EXTRA: The KB article indicates this technique can also be used to see if a drive is present. In the case of checking for drive existence, however, caveats exist:

An Abort, Retry, Fail? error occurs if the drive is not formatted.

Using this technique to check for drive existence depends on device driver implementation and may not always work.

How to check if directory exists in %PATH%?

How does one check if a directory is already present in the PATH environment variable? Here’s a start. All I’ve managed to do with the code below, though, is echo the first directory in %PATH%. Since this is a FOR loop you’d think it would enumerate all the directories in %PATH%, but it only gets the first one.

Is there a better way of doing this? Something like find or findstr operating on the %PATH% variable? I’d just like to check if a directory exists in the list of directories in %PATH%, to avoid adding something that might already be there.

22 Answers 22

First I will point out a number of issues that make this problem difficult to solve perfectly. Then I will present the most bullet-proof solution I have been able to come up with.

For this discussion I will use lower case path to represent a single folder path in the file system, and upper case PATH to represent the PATH environment variable.

From a practical standpoint, most people want to know if PATH contains the logical equivalent of a given path, not whether PATH contains an exact string match of a given path. This can be problematic because:

The trailing \ is optional in a path
Most paths work equally well both with and without the trailing \ . The path logically points to the same location either way. The PATH frequently has a mixture of paths both with and without the trailing \ . This is probably the most common practical issue when searching a PATH for a match.

    There is one exception: The relative path C: (meaning the current working directory of drive C) is very different than C:\ (meaning the root directory of drive C)

Some paths have alternate short names
Any path that does not meet the old 8.3 standard has an alternate short form that does meet the standard. This is another PATH issue that I have seen with some frequency, particularly in business settings.

Windows accepts both / and \ as folder separators within a path.
This is not seen very often, but a path can be specified using / instead of \ and it will function just fine within PATH (as well as in many other Windows contexts)

Windows treats consecutive folder separators as one logical separator.
C:\FOLDER\\ and C:\FOLDER\ are equivalent. This actually helps in many contexts when dealing with a path because a developer can generally append \ to a path without bothering to check if the trailing \ already exists. But this obviously can cause problems if trying to perform an exact string match.

    Exceptions: Not only is C: , different than C:\ , but C:\ (a valid path), is different than C:\\ (an invalid path).

Windows trims trailing dots and spaces from file and directory names.
«C:\test. » is equivalent to «C:\test» .

The current .\ and parent ..\ folder specifiers may appear within a path
Unlikely to be seen in real life, but something like C:\.\parent\child\..\.\child\ is equivalent to C:\parent\child

A path can optionally be enclosed within double quotes.
A path is often enclosed in quotes to protect against special characters like , ; ^ & = . Actually any number of quotes can appear before, within, and/or after the path. They are ignored by Windows except for the purpose of protecting against special characters. The quotes are never required within PATH unless a path contains a ; , but the quotes may be present never-the-less.

A path may be fully qualified or relative.
A fully qualified path points to exactly one specific location within the file system. A relative path location changes depending on the value of current working volumes and directories. There are three primary flavors of relative paths:

  • D: is relative to the current working directory of volume D:
  • \myPath is relative to the current working volume (could be C:, D: etc.)
  • myPath is relative to the current working volume and directory
Читайте также:  Windows shell background command

It is perfectly legal to include a relative path within PATH. This is very common in the Unix world because Unix does not search the current directory by default, so a Unix PATH will often contain .\ . But Windows does search the current directory by default, so relative paths are rare in a Windows PATH.

So in order to reliably check if PATH already contains a path, we need a way to convert any given path into a canonical (standard) form. The

s modifier used by FOR variable and argument expansion is a simple method that addresses issues 1 — 6, and partially addresses issue 7. The

s modifier removes enclosing quotes, but preserves internal quotes. Issue 7 can be fully resolved by explicitly removing quotes from all paths prior to comparison. Note that if a path does not physically exist then the

s modifier will not append the \ to the path, nor will it convert the path into a valid 8.3 format.

The problem with

s is it converts relative paths into fully qualified paths. This is problematic for Issue 8 because a relative path should never match a fully qualified path. We can use FINDSTR regular expressions to classify a path as either fully qualified or relative. A normal fully qualified path must start with : but not : , where is either \ or / . UNC paths are always fully qualified and must start with \\ . When comparing fully qualified paths we use the

s modifier. When comparing relative paths we use the raw strings. Finally, we never compare a fully qualified path to a relative path. This strategy provides a good practical solution for Issue 8. The only limitation is two logically equivalent relative paths could be treated as not matching, but this is a minor concern because relative paths are rare in a Windows PATH.

There are some additional issues that complicate this problem:

9) Normal expansion is not reliable when dealing with a PATH that contains special characters.
Special characters do not need to be quoted within PATH, but they could be. So a PATH like C:\THIS & THAT;»C:\& THE OTHER THING» is perfectly valid, but it cannot be expanded safely using simple expansion because both «%PATH%» and %PATH% will fail.

10) The path delimiter is also valid within a path name
A ; is used to delimit paths within PATH, but ; can also be a valid character within a path, in which case the path must be quoted. This causes a parsing issue.

So we can combine the

s modifier and path classification techniques along with my variation of jeb’s PATH parser to get this nearly bullet proof solution for checking if a given path already exists within PATH. The function can be included and called from within a batch file, or it can stand alone and be called as its own inPath.bat batch file. It looks like a lot of code, but over half of it is comments.

The function can be used like so (assuming the batch file is named inPath.bat):

Typically the reason for checking if a path exists within PATH is because you want to append the path if it isn’t there. This is normally done simply by using something like path %path%;%newPath% . But Issue 9 demonstrates how this is not reliable.

Another issue is how to return the final PATH value across the ENDLOCAL barrier at the end of the function, especially if the function could be called with delayed expansion enabled or disabled. Any unescaped ! will corrupt the value if delayed expansion is enabled.

Оцените статью