Solved

Batch FIle delete files with particular date

Posted on 2016-10-18
10
98 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
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
LVL 53

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 53

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
 
LVL 53

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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
ICACL switch help. How to include current folder 2 51
how to export this list 4 61
Debug script powershell wmi 3 16
Create .bat File 16 37
Being a system administrator some time we require to do things remotely, one of them is installing software. Here I am going to tell you how to install software through wmic (Windows management instrument console). I am not at all saying that this i…
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 modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
The viewer will learn how to count occurrences of each item in an array.

828 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