Solved

batch file question in deleting files

Posted on 2013-06-04
15
493 Views
Last Modified: 2013-06-13
I currently have a batch file that almost does what I need it to do. This script deletes everything in the specified folder or I can specify a file type to keep.

What I need to do is, I would like for a script to be able to specify to ONLY delete a certain type of file, and keep every other file in the same directory.  I also would like the script to keep for example 5 copies of extension .pdf, but delete the oldest ones and only keep the 5 newest according to the date.  Basically, to be able to specify which extension I need deleted and how many of the newest files to keep.  

So this is what I have so far, but I'm not sure how to modify it, or create a new script to do what I need it to do.  I need something that will work in a batch file.


@echo off (delete all files in this directory)
set BaseDir=C:\Users\dan\Desktop\test
set FilesToKeep=3
set FileFiler=*.pdf
for /R "%BaseDir%" %%D in (.) do (
  echo Processing directory "%%~fD"
  for /F "skip=%FilesToKeep% tokens=*" %%F in ('dir /A-D /O-D /B "%%~fD\%FileFilter%" 2^>NUL') do (
    del "%%~fD\%%~F"
  )
)
0
Comment
Question by:afacts
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
  • 2
  • +1
15 Comments
 
LVL 43

Expert Comment

by:Steve Knight
ID: 39220163
on phone so cant check in detail but you have set filefiler in the set statement rather than set filefilter= so it would not work as expected.

some other similar ones on http://scripts.dragon-it.co.uk and will look back on pc in a bit if not already fixdd.

steve
0
 
LVL 43

Expert Comment

by:Steve Knight
ID: 39220369
Here is one of the examples I meant:
http://scripts.dragon-it.co.uk/links/batch-versioning-backup

What you have at the moment looks for the files in each subdir of your base dir.  Is that what you want, or just the files in one dir?

Steve
0
 
LVL 43

Expert Comment

by:Steve Knight
ID: 39220382
If you do just want the one specified directory try this:

@echo off (delete all files in this directory)
set BaseDir="%userprofile%\Desktop\test"
set FilesToKeep=5
set FileFiler=*.pdf
for /F "skip=%FilesToKeep% tokens=*" %%F in ('dir /A-D /O-D /B "%BaseDir%\%FileFilter%" 2^>NUL') do (
    echo Deleting %%~F [Date: %%~tF]
    ECHO del "%BaseDir%\%%~F"
)

Remove the word ECHO to make it do the deletes rather than showing them

Steve
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:afacts
ID: 39220557
well, what your script did is delete everything in that directory except PDF's, but that's not what I need, I need the script to delete ONLY PDF's let say, and not touch any other file.
0
 

Author Comment

by:afacts
ID: 39220560
the other thing I need, is basically a script that keeps the newest files, but delete everythings that is older, for example files and the files that are deeper in folders.
0
 
LVL 43

Assisted Solution

by:Steve Knight
Steve Knight earned 166 total points
ID: 39220601
Sorry, my mistake I copy/pasted the same error from your original script I mentioned earlier "FileFiler" vs "FileFilter"

Tested this on a dir full myself and it worked fine.  Adjust the "FilesToKeep" and it shows more or less files to delete.

@echo off 
set BaseDir="%userprofile%\Desktop\test"
set FilesToKeep=5
set FileFilter=*.pdf
pushd "%BaseDir%"
for /F "skip=%FilesToKeep% tokens=*" %%F in ('dir /A-D /O-D /B "%BaseDir%\%FileFilter%" 2^>NUL') do (
    echo Deleting %%~F [Date: %%~tF]
    ECHO del "%BaseDir%\%%~F"
)
popd

Open in new window


Steve
0
 

Author Comment

by:afacts
ID: 39220697
thanks, I think that works for everything in the directory specified, but how do you make it delete everything in subfolders as well.
0
 
LVL 54

Expert Comment

by:Bill Prew
ID: 39220918
Seems like all you had to do was correct the one typo, as below.  Does this work?

@echo off
set BaseDir=C:\Users\dan\Desktop\test
set FilesToKeep=5
set FileFilter=*.pdf
for /R "%BaseDir%" %%D in (.) do (
  echo Processing directory "%%~fD"
  for /F "skip=%FilesToKeep% tokens=*" %%F in ('dir /A-D /O-D /B "%%~fD\%FileFilter%" 2^>NUL') do (
    del "%%~fD\%%~F"
  )
)

Open in new window

~bp
0
 
LVL 43

Expert Comment

by:Steve Knight
ID: 39221139
Yes that is what I said originally before I offered the option of doing just one dir.

Note this is 5 newest files in each subdir, NOT across the directory structure in general, that would be a lot more involved.

steve
0
 

Author Comment

by:afacts
ID: 39224188
I'm a little lost guys.  So what happened is I have a folder where I backup all my SQL files/folders to a backup server.  
So to keep that folder from just getting insanly big, I just need this script to run to keep let's say the 1000 newest files and delete anything older than that.

Also, I backup my website files/folders as well, and need to do the same there, but with the website backups, there's sometimes multiple layers deep, so I just need to keep the newest ones as well there as well.
0
 
LVL 54

Assisted Solution

by:Bill Prew
Bill Prew earned 167 total points
ID: 39224361
So, it sounds like you basically want to search a particular folder, and then delete files older than a certain number of file, like 100, etc.  The big question is are there subfolders (sounds like there are), and if so how do you want that to work? Gather up all the files from all the subfolders, sort by date and keep a specified number?

Rather than keeping a certain number of files, what about keeping a certain number of days, that might make more sense in this case?  In this case here's a flexible VBS script where you can specify certain options and then purge files from a folder, or folder tree. Let me know if you have questions on this approach.

' Set processing mode flags
Const ProcessSubFolders = True
Const RemoveEmptyFolders = False
Const DateToUse = "C"    ' C=created, M=modified, A=accessed

' Create file system object
Set objFSO = WScript.CreateObject("Scripting.FileSystemObject")

' Remove old files as needed
RemoveOldFiles objFSO.GetFolder("d:\", 30)
RemoveOldFiles objFSO.GetFolder("e:\", 30)
RemoveOldFiles objFSO.GetFolder("f:\", 30)

Sub RemoveOldFiles(objFolder, intDays)
    ' Remove any files older than specified days from this folder
    For Each objFile In objFolder.Files
        
        ' Get the desired date for the age check        
        Select Case UCase(DateToUse)
           Case "C"
              datFile = objFile.DateCreated
           Case "M"
              datFile = objFile.DateLastModified
           Case "A"
              datFile = objFile.DateLastAccessed
           Case Else
              datFile = objFile.DateLastModified
        End Select

        If DateDiff("d", datFile, Now) > intDays Then 
            Wscript.Echo "Deleted file: " & objFile.Path
            objFile.Delete
        End If
    Next

    If ProcessSubFolders Then
        ' Remove all older files in any subfolders of this one
        For Each objSubFolder In objFolder.Subfolders
            RemoveOldFiles objSubFolder, intDays
        Next
    End If

    If RemoveEmptyFolders Then
        ' If folder is now empty, remove it
        If objFolder.Files.Count = 0 And objFolder.Subfolders.Count = 0 Then
            Wscript.Echo "Deleted folder: " & objFolder.Path
            objFolder.Delete
        End If
    End If
End Sub

Open in new window

~bp
0
 
LVL 70

Expert Comment

by:Qlemo
ID: 39224816
I understand it that way that the folders should be treated as files. So older folders should be removed as a whole, without looking into their files. Am I correct with that?
0
 

Author Comment

by:afacts
ID: 39226682
I never thought about that.  Actually, In looking at what my program is doing, it looks like it just over rights the files, so I probalby don't need to run a script for that directory, I'm good there.

I guess I just need two scripts to do the following:

I have a folder MSSQL that stores all the .bak files, so I just need a script to keep the newest 1000 files lets say by date, and delete anything over 1000 files that, that are older than the newest 1000 files.

The second script, I have a folder that has a folder and two diferent kinds of files in the folder.
I just need it to ONLY delete .tib files, that again lets say if there's more than 5 files.  So the 6th olded file and 7th, etc... would get deleted.

Does that make sense?
0
 
LVL 70

Accepted Solution

by:
Qlemo earned 167 total points
ID: 39226755
Both can get managed by http:#a39220601 . You just need to call it with the vars at the beginning set up for each case, or we implement a "procedure" with parameters:
@echo off 
call RemoveOld "%userprofile%\Desktop\test" 1000 *.bak
call RemoveOld "C:\AcronisBackups\Folder1\" 5 *.tib
exit /b

:RemoveOld  BaseDir FilesToKeep FileFilter
set BaseDir=%~1& shift
set FilesToKeep=%1& shift
set FileFilter=%1& shift
pushd "%BaseDir%"
for /F "skip=%FilesToKeep% tokens=*" %%F in ('dir /A-D /O-D /B "%BaseDir%\%FileFilter%" 2^>NUL') do (
    echo Deleting %%~F [Date: %%~tF]
    ECHO del "%BaseDir%\%%~F"
)
popd
exit /b

Open in new window

0
 

Author Closing Comment

by:afacts
ID: 39246408
Thanks for the help guys!
0

Featured Post

Why You Need a DevOps Toolchain

IT needs to deliver services with more agility and velocity. IT must roll out application features and innovations faster to keep up with customer demands, which is where a DevOps toolchain steps in. View the infographic to see why you need a DevOps toolchain.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Batch, VBS, and scripts in general are incredibly useful for repetitive tasks.  Some tasks can take a while to complete and it can be annoying to check back only to discover that your script finished 5 minutes ago.  Some scripts may complete nearly …
Active Directory replication delay is the cause to many problems.  Here is a super easy script to force Active Directory replication to all sites with by using an elevated PowerShell command prompt, and a tool to verify your changes.
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
The viewer will learn how to dynamically set the form action using jQuery.

740 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question