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

Reading Time: 2 minutes
Cmd.exe: Workaround for “if not exist *.*” and other uses for the FOR command
Rate this post

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

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

Get the count of all subfolders in folder c:\test, and test on 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):

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.

Source: old site

Share