Monday 27 January 2014

Microsoft: Delete Files after a Certain Number of Days

You may delete the file(s)  after a certain number of days with the ForFiles command.
forfiles -p "C:\what\ever" -s -m *.* /D -<number of days> /C "cmd /c del @path"

FORFILES.exe (Native command in Vista/Windows7/2008, via Resource Kit for XP)
Select a file (or set of files) and execute a command on each file. Batch processing.

Syntax
      FORFILES [/p Path] [/m SrchMask] [/s] [/c Command] [/d [+ | -] {date | dd}]

Key
  • /p Path: The Path to search  (default=current folder)
  • /m SrchMask: Select files matching the specified search mask (default = *.*)
  • /s: Recurse into sub-folders
  • /C command: The command to execute for each file. Wrap the command string in double quotes. Default = "cmd /c echo @file" The Command variables listed below can also be used in the command string.
  • /D date: Select files with a last modified date greater than or equal to (+), or less than or equal to (-), the specified date, using the region specific date format typically "MM/DD/yyyy" or "DD/MM/yyyy"
  • /D + dd: Select files with a last modified date greater than or equal to the current date plus "dd" days. (in the future)
  • /D - dd: Select files with a last modified date less than or equal to the current date minus "dd" days. (in the past) A valid "dd" number of days can be any number in the range of 0 to 32768.   (89 years) "+" is taken as default sign if not specified.
   Command Variables:
  • @file: The name of the file
  • @fname: The file name without extension            
  • @ext: Only the extension of the file            
  • @path: Full path of the file
  • @relpath: Relative path of the file      
  • @isdir: Returns "TRUE" if a file type is a directory and "FALSE" for files                
  • @fsize: Size of the file in bytes
  • @fdate: Last modified date of the file
  • @ftime: Last modified time of the file
To include special characters in the command line, use the hex code for the character in 0xHH format (ex. 0x09 is theTAB character, 0x22 is the double quote " character.) so "C:\Program Files\" becomes ^0x22C:\Program^ Files\^0x22

Internal CMD.exe commands must be preceded with cmd /c

If ForFiles finds one or more matches if will return %errorlevel% =0
If ForFiles finds no matches if will return %errorlevel% =1 and will print "ERROR: No files found with the specified search criteria."

Early versions of FORFILES were supplied in the NT resource kits and used unix style '-' parameters, (still supported for backwards compatibility) also the /D option accepted dates only in DDMMYYYYHHMN format.

Last modified dates set in the future are not common but can happen when your computer clock date/time is changed e.g. due to daylight savings time.


Reference:
FORFILES.exe
http://ss64.com/nt/forfiles.html

No comments:

Post a Comment