Cmd.exe: Workaround for “if not exist *.*” and other uses for the FOR command

One of the annoying things in Windows XP/2003 and later, is that the construct

if not exist c:\test\*.* echo No files!

does not work as expected if c:\test is empty.

This seems to be due to the fact that Windows regards the “.” and “..” file entries as valid files (even though, technically they are directories), so the command above never displays the text.

One workaround for this is to use a construct using the FOR command.

Here are some examples that address different problems and their solutions.

Note: Be advised that these commands will work from the interactive cmd.exe window only, if you want to use them from a batch file the percent-signs should be doubled for single-letter variables, e.g. replace %I with %%I).

Note: These examples assume that Command Extensions are enabled. These are enabled by default in Windows XP and later. For information, type cmd /? or setlocal /? in a command window.

Get the count of all files in folder c:\test, and test on an empty folder

set COUNT=0
for %I in (c:\test\*.*) do set /a COUNT+=1
if %COUNT% EQU 0 echo No files

Get the count of all subfolders in folder c:\test, and test on no subfolders

set COUNT=0
for /d %I in (c:\test\*.*) do set /a COUNT+=1
if %COUNT% EQU 0 echo No subfolders

Alternative if you need finer control over attribute selection of the items in folder c:\test

Here you can give attribute parameters to the dir command. Note the use of the for /f command to execute a command and get the resulting lines in subsequent loops in the statement after the do keyword. In this example, only files with the Archive bit set are reported (so, effectively, only the files that have changed since the last backup):

set COUNT=0
for /f %I in ('dir /b /aa c:\test\*.*') do set /a COUNT+=1
if %COUNT% EQU 0 echo No folders

Getting the filename of the oldest file in the current folder

This last example is extremely useful if you need to implement a First-In-First-Out queue based on the files’ modified time time stamps.

set FILENAME=
for /f \"tokens=*\" %I in ('dir /b /o-d') do set FILENAME=%I
if defined FILENAME (
  echo Oldest file: %FILENAME%
) else (
  echo No files!
)

Source: old site

Share