Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / batch

Forfiles.exe: deleting files

5.00/5 (2 votes)
20 Feb 2012CPOL2 min read 40.8K  
Batch file for deleting files automatically using ForFiles.exe.

Introduction


The following batch file uses "Forfiles.exe" for deleting files from the mentioned path. Forfiles.exe is supported only by Windows Vista, Windows 7, Windows Server 2003, and higher versions. Forfiles is present in the following path: c:>windows>system32. Before running the batch file, make sure that forfiles.exe is present in the path otherwise the batch file will not work. The batch file can be really useful for releasing memory from drives by deleting unnecessary files. You can also schedule it to run in Windows Server using the Task Scheduler during regular intervals.


Using the Code


In this code I have created two folders "udit_delete_test" and "udit_temp" in c:>drive of my system. Once I run this batch file, it deletes all files older than one day from the mentioned path of folders.


Description of tags in code:



  • "/p": this tag indicates the path where you want to delete files.
  • "/s": this tag helps in deleting the files recursively inside the other folders present in the folder mentioned in the batch file path.
  • "/d": the most important tag; here you can declare the days for deleting the files older than the present date. In my case, I am deleting files older than a day. This can be done using "/d -1" "-1", which means older than a day.
  • "/c": for declaring command to delete files "cmd /c del @file".

For more info on Forfiles functionality, go to command prompt and type the following: "c:\windows\system32\forfiles /?" and press Enter.


There are many other features for Forfiles but I have mentioned only the deleting feature here.


:begin
    cd\
    cd c:\windows\system32
    forfiles /p c:\udit_delete_test /s /d -1 /c "cmd /c del @FILE"
    forfiles /p c:\udit_temp /s /d -1 /c "cmd /c del @FILE"
    :end

Points of Interest


There are other ways of deleting files like "Del" and "xcopy" but Forfiles provides advantage over these as in Forfiles you can set the timing for deleting files like "files older than a particular date".


History



  • Initial version 1.0.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)