user1595923
user1595923

Reputation: 691

How to check if a directory exists with a wildcard in the directory name?

I'm trying to create a batch file that will check the existence of a directory before processing the rest of the commands. The directory name will always start the same, but then various numbers and sometimes letters are appended to the end. I would like to delete the directory at the end of the batch file, but using variables with rmdir without checking to make sure that path exists first has created issues (as in another directory being deleted). The code below is what I've been working with, but the system says this path doesn't exist.

IF EXIST "C:\Today's Unique Folder*\nul" ( GOTO continue ) ELSE ( GOTO end)

Furthermore, I tried to set this path as a variable and use the variable with IF EXIST, but that didn't work either. Is there a command other than IF EXIST that I should try? Thanks in advance for the assistance.

Upvotes: 4

Views: 8121

Answers (2)

aphoria
aphoria

Reputation: 20189

You can use FOR with the /D parameter to search for the folder name using a wildcard.

Note, if there are multiple folders found with the same beginning part of the folder name, RESULT will end up being the last folder.

SET RESULT=---

FOR /D %%d IN ("C:\Today's Unique Folder*") DO (
  SET RESULT=%%d
)

IF EXIST "%RESULT%" (GOTO WINDIR) ELSE (GOTO NOWINDIR)

:WINDIR
  ECHO Yes
  GOTO END

:NOWINDIR
  ECHO No

:END

Upvotes: 4

Brad
Brad

Reputation: 15879

According to MS KBase you're mostly right. I think you have a problem with your directory name. The following works for me using a valid directory name, and it echo's "Yes".

Try it without using double quotes around your directory name because Windowss doesn't like them in this context (strangley)

@echo off

IF EXIST C:\Program Files\NUL ( GOTO WINDIR ) ELSE ( GOTO NOWINDIR )

:WINDIR
echo Yes
goto END

:NOWINDIR
echo No

:END

Change "C:\Program Files" to something like "C:\Foo" that doesn't exist and it will echo "No"

Upvotes: 0

Related Questions