Solved

Batch FIle delete files with particular date

Posted on 2016-10-18
10
75 Views
Last Modified: 2016-10-19
I have a customer with a (much older) server with limited space and only .Net 1.1

I cannot update... yet there is a folder that receives SQL Data Base Backup files daily.

I need a DOS? script that
Looks in the backup folder
Finds the most recent file with the .BAK extension (Even if the most recent .bak file is 100 days old...)
And deletes any file older that 3 days from that file date and that .BAK extension
0
Comment
Question by:lrbrister
  • 4
  • 3
  • 3
10 Comments
 
LVL 26

Expert Comment

by:Zberteoc
ID: 41848951
If you want to remove files older than a certain number of days is easy. If you want to look at the oldest file date and remove the ones older than a certain number of days before that is complicated in a batch file.

First option:

REM Remove files backup older than 3 days
forfiles /p "C:\backupfolder" /s /m *.bak /c "cmd /c Del @path" /d -3
0
 

Author Comment

by:lrbrister
ID: 41848953
Basically what I want is to find the NEWEST file in the folder
THEN set the - days from that date
0
 
LVL 26

Expert Comment

by:Zberteoc
ID: 41849000
All I can do is to delete all the files except the most recent one:

@ECHO OFF
FOR /F %%I IN ('DIR *.bak /B /O:-D') DO SET last=%%I & GOTO EOF

:EOF
echo %last%
echo ------------
for %%i in (*.bak) do if not %%i == %last% del %%i

Open in new window

Just so you know I edited the code. Use it now.
0
 
LVL 52

Expert Comment

by:Bill Prew
ID: 41849024
I will put something together when I get a few minutes later today or early tomorrow...

~bp
0
 
LVL 52

Expert Comment

by:Bill Prew
ID: 41850163
Would you be okay with a VBS solution rather than a BAT one?  I could work it out in either, but it would be easier for the date checking in VBS.

~bp
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 52

Accepted Solution

by:
Bill Prew earned 500 total points
ID: 41850542
Okay, here is a VBS script that does what you described and tested well here.  Save as a VBS files, edit the folder, extension and days to purge settings near the top, and run as follows.  Test very thoroughly since this will delete files.  Also there is logging to a file in the folder where the script is run from with the name of the script and an extension of .log.  Wasn't sure what you wanted to log, or where, but it gives you a starting point.

cscript EE28977174.vbs

' Text file I/O constants
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
Const TristateTrue = -1
Const TristateFalse = 0
Const TristateUseDefault = -2

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

' Define folder and files to work with
strBaseDir = objFSO.GetAbsolutePathName("B:\EE\EE28977174\Files")
strPurgeExtension = ".bak"
intPurgeDays = -3
strLogFile = Replace(WScript.ScriptFullName, ".vbs", ".log", 1, -1, vbTextCompare)

' Open log file for appending
Set objLog = objFSO.OpenTextFile(strLogFile, ForAppending, True)
LogStart

' Quit if base folder does not exist
If Not objFSO.FolderExists(strBaseDir) Then
   objLog.WriteLine Now & " ERROR: Base folder does not exist: " & strBaseDir
   LogEnd
   Wscript.Quit
End If

' Determine date of most recent file
datLatestFile = FindLatestFile()

' If we found a file, then purge files older than the desired days from that newest file date
If datLatestFile <> 0 Then
   PurgeOldFiles DateAdd("d", intPurgeDays, datLatestFile)
End If

' Wrap up
LogEnd
Wscript.Quit


Function FindLatestFile()
   Set objFolder = objFSO.GetFolder(strBaseDir)
   FindLatestFile = 0

    ' Look at all files in this folder
   For Each objFile In objFolder.Files
      ' Make sure it matches the files we are looking for
      If LCase(Right(objFile.Name, Len(strPurgeExtension))) = LCase(strPurgeExtension) Then
         ' Assume very first file is newest until we find a newer one
         If FindLatestFile = 0 Then
            FindLatestFile = objFile.DateLastModified
            strLatestFileName = objFile.Name
         ' Otherwise see if this file is the newest of all seen so far
         Else
            If objFile.DateLastModified > FindLatestFile Then
               FindLatestFile = objFile.DateLastModified
               strLatestFileName = objFile.Name
            End If
         End If
      End If
   Next

   ' Log info on latest file found
   If FindLatestFile = 0 Then
      objLog.WriteLine Now & " WARNING: No backup files found."
   Else
      objLog.WriteLine Now & " INFO: Newest file name: " & strLatestFileName
      objLog.WriteLine Now & " INFO: Newest file date: " & FindLatestFile
   End If
End Function

Sub PurgeOldFiles(datPurgeDate)
   Set objFolder = objFSO.GetFolder(strBaseDir)

   ' Look at each file in the folder
   For Each objFile In objFolder.Files
      ' Look at previously processed files, remove ones that are older than threshold
      If LCase(Right(objFile.Name, Len(strPurgeExtension))) = LCase(strPurgeExtension) Then
         ' If older than purge date then delete this file
         If objFile.DateLastModified < datPurgeDate Then
            objLog.WriteLine Now & " INFO: Purged old file: " & objFile.Name
            objFile.Delete
         End If
      End If
   Next
End Sub

Sub LogStart()
   ' Log script start
   objLog.WriteLine Now & " INFO: ==============================================================================="
   objLog.WriteLine Now & " INFO: Started script: """ & Wscript.ScriptName & """."
End Sub

Sub LogEnd()
   ' Log script end
   objLog.WriteLine Now & " INFO: Ended script: """ & Wscript.ScriptName & """."
   objLog.WriteLine Now & " INFO: ==============================================================================="
   objLog.Close
End Sub

Open in new window

~bp
0
 

Author Comment

by:lrbrister
ID: 41850552
Testing now
0
 

Author Closing Comment

by:lrbrister
ID: 41850681
Perfect... thanks
0
 
LVL 26

Expert Comment

by:Zberteoc
ID: 41850736
I am sure it works, but that is a very big piece of code and I am for simplification:
Option Explicit  
Dim fso, path, file, recentDate, recentFile, folder, daysold
Set folder="C:\temp"
Set daysold=3
Set fso = CreateObject("Scripting.FileSystemObject")
Set recentFile = Nothing
For Each file in fso.GetFolder(folder).Files
  If LCase(fso.GetExtensionName(file.Name)) = "bak" Then
	  If (recentFile is Nothing) Then
		Set recentFile = file
	  ElseIf (file.DateLastModified > recentFile.DateLastModified) Then
		Set recentFile = file
	  End If
  End If
Next

If recentFile is Nothing Then
	WScript.Echo "no recent files"
Else
	Set recentDate=recentFile.DateLastModified

	For Each file in fso.GetFolder(folder).Files
	  If LCase(fso.GetExtensionName(file.Name)) = "bak" Then

		If DateDiff("d", file.DateLastModified, recentDate) > daysold Then
			file.Delete(True)
		End If	  
	  
	  End If
	Next

End If

Open in new window

0
 

Author Comment

by:lrbrister
ID: 41850930
Thanks guys
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

It is a general practice to get rid of old user profiles on a computer  in a LAN environment. As I have been working with a company in a LAN environment where users move from one place to some other place at times. This will make many user profil…
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 how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

932 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now