Reporting failed to delete to a file in DEL batch files

房东的猫 提交于 2019-12-11 13:02:24

问题


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?


回答1:


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)



回答2:


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.



来源:https://stackoverflow.com/questions/16179611/reporting-failed-to-delete-to-a-file-in-del-batch-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!