JSI Tip 6415. How can a batch script test if a folder is empty, or contains folders, files, or both folders and files?

Jerold Schulman

March 6, 2003

1 Min Read
ITPro Today logo in a gray background | ITPro Today


I have scripted FFExist.bat to allow a batch file to determine if a folder is empty, or containssub-folders, or contains files, or contains both sub-folders and files.

The syntax for using FFExist.bat is:

call ffexist FolderPath Answer

where:

FolderPath is the path to the folder, like "C:Program Files", and Answer is a call directed environment variable that will be set as follows:

XX - The FolderPath does NOT exist.NN - The FolderPath is empty.YN - The FolderPath contains sub-folders and does NOT contain files.NY - The FolderPath contains files and does NOT contain sub-folders.YY - The FolderPath contains both sub-folders and files.

NOTE: If you fail to specify the Answer argument, FFExist.bat displays Syntax: ffexist FolderPath Answer.

NOTE: If you only need to determine if the FolderPath is empty, you could use the following command line:

dir /b /a FolderPath|findstr .>nul:&&(goto :notmt)||(goto :mt)

NOTE: The above command makes use of the findstr wildcard (.) and the conditional processing symbols.

FFExist.bat contains:

@echo offif {%2}=={} @echo Syntax: ffexist FolderPath Answer&goto :EOF setlocalif not exist %1 endlocal&set %2=XX&goto :EOFdir %1 /a|findstr /c:" 0 File">NUL:&&(set file=N)||(set file=Y)dir %1 /a|findstr /c:" 2 Dir">NUL:&&(set fold=N)||(set fold=Y)endlocal&set %2=%fold%%file%



Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like