RpTheHotrod
RpTheHotrod

Reputation: 185

Reporting failed to delete to a file in DEL batch files

How does one create a report file where a DEL command failed to execute properly?

I would have thought you'd do:

DEL FILENAME.TXT ECHO "FILENAME.TXT" >> REPORT.TXT

but all it does is make an empty report file, regardless of if it finds FILENAME.TXT or not. I'm wanting to create a report file where if it failed to delete FILENAME.TXT for whatever reason that the message that pops up is dumped into REPORT.TXT.

Any ideas?

Upvotes: 2

Views: 1959

Answers (2)

Explorer09
Explorer09

Reputation: 724

Just for your information. The DEL command does return an error code if a serious error occurs, however it's behavior is way beyond our intuition that people would simply believe that the error code doesn't work at all.

This is what I've tested in DEL command in Windows 7:

  • Successful deletion of all files: 0 (of course)
  • Some files deleted, some files missing: 0 (intuition expects 1)
  • Deletion failure due to no permission or a read-only medium: 0 (intuition expects ≥ 1)
  • Non-existent drive or drive not ready (such as no CD on a CD-ROM drive): 1 (yes, you get it, but I will expect a higher error code)
  • Invalid path: 1 (I will expect a higher error code, too)

And, if you specify a list of files to DEL command, where at least one of the files fit the last two kinds of error mentioned above, then none of the files in the list will be deleted at all.

Upvotes: 5

ElektroStudios
ElektroStudios

Reputation: 20464

The Del command always returns errorcode 0 even if file is not found or if file need admin access, so you need to check if file still exist after trying to delete it:

@Echo OFF

Set "File=File.txt"

Del "%File%" 2>NUL & If exist "%File%" (
    Echo [+] File failed to delete: "%File%" >> "Report.txt" 
)

Pause&Exit

For a large amount of files you can make a procedure to not write a large code, like this:

@Echo OFF

Call :ReportDelete "C:\File1.txt"
Call :ReportDelete "C:\File2.txt"
Call :ReportDelete "C:\File3.txt"
Call :ReportDelete "C:\File4.txt"
Call :ReportDelete "C:\File5.txt"

Pause&Exit

:ReportDelete
(Del "%~1" 2>NUL & If exist "%~1" (Echo [+] File failed to delete: "%~1" >> "Report.txt")) & (Goto:EOF)

Upvotes: 0

Related Questions