Thursday, January 13, 2011

Find and Remove Zero Byte files

I often create batch files for various tasks. I have an application that dumps files to certain folders each day. It also creates zero byte files if there was no activity. I found the need to check the folder each day prior to uploading to another location to look for such files and remove them. The solution was a simple batch file run as a scheduled task each night.

Below are the main two commands you need to do this:

set "filemask=*.txt"
for %%A in (%filemask%) do if %%~zA==0 del /F /Q "%%A"

In the first command you can set the variable for what files you want to apply this to. You could use just the * and search all files or you can add some parameters, like the example above that will look at all txt files. In the second command, the part "del /F /Q" says to delete the file, to force delete and do so without prompting. This could be changed to anything for example you could use the echo command to output a list of files instead (see ex below).

You will also want to either run the bat from the location you want it to search in or you will need to specify the location in the file. For example a finished version of the bat file might look something like this:

@echo off

set "filemask=*.log"

d:
cd d:/folder1
 
for %%A in (%filemask%) do if %%~zA==0 del /F /Q "%%A"

c:
cd c:/folder2

for %%A in (%filemask%) do if %%~zA==0 echo "%%A" >> zerobytefiles.txt

exit


In addition, if you need to create a 0 byte file for testing, about the easiest way to do so is with this command: cd.>zerobyte.txt

No comments:

Post a Comment