Delete all files older than 7 or X days with Batch DOS


To totally unlock this section you need to Log-in


Login

Sometime we need some little simple tool to check and delete files in a specified directory on a system. To achieve this goal we could search some third-party tool (and pay for it) or create this tool by scratch. Multiple programming language could be involved to calculate the oldness of a set of files, but a simple one is commonly better to mantain (and to study).

By the way, here is a simple-little code, written in batch DOS, to compare dates and delete (in this example this code will only print WHAT will be deleted, but it will doesn't delete anything) files older than 7 days (this parameter can be modified specifying the value in:

set /a strip=day*7

To do a reliable check about dates in this batch there is a simple function to convert the date of each file, in a directory, to epoch (UNIX) time.

Delete all files older than 7 or X days with Batch DOS

Delete all files older than 7 or X days with Batch DOS

However this function, in this solution, does not consider leap years from 1970 (11 days, so in UNIX time 950400). This does not undermines the functionality of thi batch DOS for common use.

[tweet]

The Logic

To calculate the whole UNIX time of a date will need to calculate separately:

  • Days from the beginning of the Month, in seconds;
  • Months based on Days, calculated in seconds;
  • Years based on Days, calculated in seconds;

So, for example, for 25/07/2013 (DD/MM/YYYY) will need to do some little calculations:

Day = 25 x 86400 (seconds);

Year = (2013-1970) x (86400 x 365);

For months will need to calculate seconds from January to the actual month minus 1. For example, for July:

Months = 86400 x (31+28+31+30+31+30)

To totally unlock this section you need to Log-in


Login

1 thought on “Delete all files older than 7 or X days with Batch DOS”

Comments are closed.