Link to home
Start Free TrialLog in
Avatar of Rich55555
Rich55555Flag for Australia

asked on

Windows Batch - Find Folder & Delete Files

I need to search a folder structure to check if certain folders exist, if they do then need to delete the files in the folders which are 14 days+ old.

Example of folder structure:

c:\tobe\letters\reject\
c:\bech\letters\printed\
c:\aiki\pollo\
c:\obbo\cricket\
c:\itsa\letters\reject\
c:\lana\letters\printed

Ideally I want to search c:\*.*\letters\ if 'reject' or 'printed' folders exist then delete files older than 14 days in c:\*.*\letter\reject & c:\*.*\letters\printed.

The script structure should be:
1. A FOR statement looping through and searching c:\*.*\letters\
2. IF EXIST 'reject' folder THEN do FORFILES cmd to delete files older than 14 days
3. IF EXIST 'printed' folder THEN do FORFILES cmd to delete files older than 14 days

Some of the code I've been tinkering with, as you can see I'm struggling :\
REM Some code I've been tinkering with
 
for /d %a in ("c:\*") do echo c:\%a\letters\
if exist c:\%a\letters\reject
forfiles /p   c:\*.*\letters\reject\* /s /m*.* /dt-14 /c"cmd /c echo @file"

Open in new window

Avatar of manavsi
manavsi
Flag of India image

You might want to consider using a language that is better suited for this task.

My preference would be to use Perl. Perl can do in 1 line of code everything that your current batch file does, excluding the echo statements. The echo statements would be about the same, but Perl can even do that part in fewer lines. Perl can also very easily traverse a directory tree and delete only the desired files.
#!perl -w
 
use strict;
use File::Find;
 
usage() if (! @ARGV || $ARGV[0] =~ /\D/);
 
my $age = $ARGV[0];
my $dir = $ARGV[1] || '.';
 
find(sub { print "$_\n" if -M $_ > $age; }, $dir);
 
sub usage {
print <<'EOF';
USAGE:
DELOLD X [Dir]
Where:
X is the number of days previous to Today.
Dir is the optional directory where files exist. Defaults to current directory.
 
EX: "DELOLD 5" Deletes files older than 5 days.
"DELOLD 120 c:\temp" Deletes files from the c:\temp directory that are older than 120 days.
EOF
}

Open in new window

may be calling this perl script with ur batch file can help u i suppose.. :)


HTH
Manavsi
ASKER CERTIFIED SOLUTION
Avatar of manavsi
manavsi
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Rich55555

ASKER

Manavsi, definately wanted to do this in batch file.

Your batch file seems complex, could that not be simplified with the 'forfiles' command?