Jump to content

Delete Files Older Than x Days - ForFiles.exe - Script Issues


Recommended Posts

Posted

Hi,

 

I'm having a little issue with a batch script that I've managed to create, using information from various posts and forums on the web but can't quite get it right.

 

Can anyone offer any help?

 

I'm wanting the script to check a folder's contents by the age and delete anything over 5 days old, the script I have at the minute is as follows:

 

 

forfiles /p "C:\CCTV\Channel1\" /s /D -5 /M *.* -C "cmd /C del /Q"

 

 

The command prompt then opens and lists a lot of files but then nothing is deleted once the process is complete.

 

Thanks in advance

Posted (edited)

Here is what I use:

 

forfiles /p C:\Folder\archive /s /Filename.* /d -8 /c "cmd /c del @FILE"

 

Edit:

Explaination This deletes all files named Filename from C:\Folder\archive over 8 days old.

Edited by creese
  • Thanks 1
Posted

Thanks for the reply :D Unfortunately... no luck :confused:

 

I tried copying your text:

 

forfiles /p C:\Folder\archive /s /Filename.* /d -8 /c "cmd /c del @FILE"

 

but changing it to suit my needs

 

forfiles /p C:\CCTV\Channel1/s /Filename.* /d -5 /c "cmd /c del @FILE"

 

and the command prompt flashed up for a split second before disappearing and once again nothing had been done. So I put a pause in to see what had been done and this is what I've got:

 

 

C:\CCTV\Channel1>forfiles /p C:\CCTV\Channel1 /s /FILENAME.* /d -5 /c "cmd /c de

l @FILE"

FORFILES v 1.1 - by Emmanuel Boersma - 4/98

 

 

Syntax : FORFILES [-pPath] [-mSearch Mask] [-ccommand] [-dDDMMYY] [-s]

 

-pPath Path where to start searching

-mSearch Mask Search files according to

-cCommand Command to execute on each file(s)

-d[+|-][DDMMYY|DD] Select files with date >= or <=DDMMYY (UTC)

or files having date >= or <= (current date - DD days)

-s Recurse directories

-v Verbose mode

 

The following variables can be used in Command :

@FILE, @PATH, @RELPATH, @ISDIR, @FSIZE, @FDATE, @FTIME

 

 

Default :

Examples :

FORFILES -pc:\ -s -m*.BAT -c"CMD /C Echo @FILE is a batch file"

FORFILES -pc:\ -s -m*.* -c"CMD /C if @ISDIR==TRUE echo @FILE is a directory"

FORFILES -pc:\ -s -m*.* -d-100 -c"CMD /C Echo @FILE : date >= 100 days"

FORFILES -pc:\ -s -m*.* -d-010193 -c"CMD /C Echo @FILE is quite old!"

 

C:\CCTV\Channel1>pause

Press any key to continue . . .

 

Any idea?

 

Could it possibly be my version of forfiles.exe that I've downloaded? I got it from here

Any help is greatly appreciated

Posted

This is the script I use for deleting SIMS and FMS backups older than 7 days. Obviously using *.* will delete any files in the given directory older than 7 days.

 

FORFILES /P "D:\Program Files\Microsoft SQL Server\MSSQL10.SIMS2008\MSSQL\Backup" /S /M *.* /D -7 /C "CMD /C del /Q @FILE"

  • Thanks 1
Posted

Now you have me confused. :D

 

You have

C:\CCTV\Channel1>forfiles /p C:\CCTV\Channel1 /s /FILENAME.* /d -5 /c "cmd /c de

l @FILE"

 

It should be

forfiles /p C:\CCTV\Channel1 /s /FILENAME.* /d -5 /c "cmd /c de

l @FILE"

 

It's stopping after

C:\CCTV\Channel1>

 

If you want to delete all files change FILENAME to * or it will only delete files called FILENAME

Posted
This is the script I use for deleting SIMS and FMS backups older than 7 days. Obviously using *.* will delete any files in the given directory older than 7 days.

 

FORFILES /P "D:\Program Files\Microsoft SQL Server\MSSQL10.SIMS2008\MSSQL\Backup" /S /M *.* /D -7 /C "CMD /C del /Q @FILE"

 

Again nothing. Doesn't even whizz through all the files.

 

You have

C:\CCTV\Channel1>forfiles /p C:\CCTV\Channel1 /s /FILENAME.* /d -5 /c "cmd /c de

l @FILE"

The C:\CCTV\Channel1> bit before the forfiles /p C:\CCTV was from Command prompt and not actually text in the batch file. That was what I was left with after running the batch using the script you left.

 

If you want to delete all files change FILENAME to * or it will only delete files called FILENAME

I've also tried it both ways with no luck.

 

I have found that if I use the script you have both mentioned:

 

forfiles /p C:\CCTV\Channel1 /s /FILENAME.* /d -5 /c "cmd /c del @FILE"
-

if I put a \ on the end of my directory path so its -

forfiles /p C:\CCTV\Channel1\ /s /FILENAME.* /d -5 /c "cmd /c del @FILE"
-

 

then it whizzes through all the files in the folder as though it's actually checking the files but it is still not deleting them.

I have files in their since the 1st of Januray 2011 so the 5days shouldn't be a problem.

 

 

Sorry to be a pain

Posted (edited)
Sorry to be a pain

 

No need to be sorry.

 

If you are still using FILENAME change it to an asterix * that will then delete all files. It is looking for a file called FILENAME. I use it to select certain filenames, it seems you don't want to select. Does that make sense. the FILENAME bit is mine not the forfiles.

 

so

forfiles /p C:\CCTV\Channel1\ /s /m *.* /d -5 /c "cmd /c del @FILE"

 

Oops. Just realised I left out the /m bad editing

Edited by creese
Posted
If you are still using FILENAME change it to an asterix * that will then delete all files.

I tried this at the beginning with no luck... I've also tried replacing filename with one of the actual names of a file and again nothing.

 

Also, all the files are .raw files so I also tried *.raw but still no luck... I'm guessing that would be right < ? I've never used forfiles before.

 

 

Are the files to be deleted in the Channel1 directory, if so you probably don't need the \ after it.

The files to be deleted are in the channel1 directory but without the \ it just shows the same as it would if i opened command prompt and typed in "forfiles"

Posted

Yes it's definitely installed, I've just got it today... but possibly an earlier version?

 

I'll download the one you've linked tomorrow when I'm back at work and let you know the results.

Thanks again

Posted
I'm wanting the script to check a folder's contents by the age and delete anything over 5 days old

One thing to keep in mind with your forfiles command is that it will delete the files regardless of whether there are new ones to take their place. For example, say there was an issue with your CCTV system and it didn't record anything for an entire week, you would end up with a completely empty Channel1 folder because all of the files are older than five days.

 

The VBScript below attempts to solve this problem by making sure that there are always five days worth of files kept, even if some of the files are actually older than five days (hopefully that makes sense?).

 

Option Explicit

CONST adFldIsNullable = &H00000020 
CONST adVarChar = 200 
CONST adDate = 7 
CONST adOpenDynamic = 2 
CONST adUseClient = 3 
Const ForReading = 1, ForWriting = 2, ForAppending = 8
' Set DEBUGOUTPUT to true to output to the console as well as logfile
CONST DEBUGOUTPUT = TRUE

Dim objFSO
Dim objFolder, colFiles, File
Dim objRunningLogFile
Dim objRS, intFailedDays, intSuccessfulDays, dteWorkingDate, dteNewestDate
Dim intDeleteFilesCount

' ******************************************************************************************
' Customization section:
'  strRunningLogFile will contain lists all last successful days, failed days, and deleted files
'  strTargetFolder is the location to scan for files, not recursive
'  DaysOfBackupsToKeep is # of days worth of data to store.  If the backups are weekly, set to 30 or more
' ******************************************************************************************
CONST strRunningLogFile = "[color="red"]C:\CCTV\RunningLog.txt[/color]"
CONST strTargetFolder = "[color="red"]C:\CCTV\Channel1[/color]"
CONST DayOfBackupsToKeep = [color="red"]5[/color]

Set objFSO = CreateObject("Scripting.FileSystemObject")  
Set objfolder = objFSO.GetFolder(strTargetFolder)

Set objRS = CreateObject("ADODB.Recordset")
With objRS
  .CursorLocation = adUseClient 
  .CursorType = adOpenDynamic
  .Fields.Append "Name", adVarChar, 255, adFldIsNullable
  .Fields.Append "Path", adVarChar, 255, adFldIsNullable
  .Fields.Append "DateMod", adDate, 32, adFldIsNullable
  .Open
End With

Set colFiles = objFolder.Files

For Each File in colFiles
  With objRS
     .AddNew
     .Fields("Name") = File.Name
     .Fields("Path") = File.Path
     .Fields("DateMod") = File.DateLastModified
     .Update
  End With
Next

objRS.Sort = "DateMod DESC"
If NOT objRS.EOF Then
  objRS.MoveFirst
End If

intFailedDays = 0
intSuccessfulDays = 0
intDeleteFilesCount = 0

dteWorkingDate = Date

Set objRunningLogFile = objFSO.OpenTextFile(strRunningLogFile, ForAppending, True)
objRunningLogFile.WriteLine vbCrLf & "------------------------------------------------------------------"
objRunningLogFile.WriteLine "Run time: " & Now
If DEBUGOUTPUT Then
  WScript.Echo "Report for " & strTargetFolder & " on " & Now
End IF
If NOT objRS.EOF Then
  objRunningLogFile.WriteLine "Most Recent Backup File dated: " & ObjRS.Fields("DateMod") & ", " &_
                              DateDiff("d", ObjRS.Fields("DateMod"), Date) & " day(s) ago."
  If DEBUGOUTPUT Then
     WScript.Echo "Most Recent Backup File dated: " & ObjRS.Fields("DateMod") & ", " &_
                   DateDiff("d", ObjRS.Fields("DateMod"), Date) & " day(s) ago."
  End If
End If

Do Until objRS.EOF
  If intSuccessfulDays < DayOfBackupsToKeep Then
     If DateDiff("d", objRS.Fields("DateMod"), dteWorkingDate) = 0 Then
        objRunningLogFile.WriteLine dteWorkingDate & ": " & vbTab & objRS.Fields("Name")
        If DEBUGOUTPUT Then
           WScript.Echo dteWorkingDate & ": " & vbTab & objRS.Fields("Name")
        End If
        intSuccessfulDays = intSuccessfulDays +1
        If intSuccessfulDays = 1 Then
           objRunningLogFile.WriteLine "Newest File: " & objRS.Fields("Name") & " - Modified: " & objRS.Fields("DateMod")
        End If
        objRS.MoveNext
        Do Until objRS.EOF
           If DateDiff("d", objRS.Fields("DateMod"), dteWorkingDate) = 0 Then
              objRunningLogFile.WriteLine vbTab & vbTab & objRS.Fields("Name")
              If DEBUGOUTPUT Then
                 Wscript.Echo vbTab & vbTab & objRS.Fields("Name")
              End If
              objRS.MoveNext
           Else
              dteWorkingDate = DateAdd("d", -1, dteWorkingDate)
              Exit Do
           End if
        Loop 
     Else
        If DateDiff("d", Date, dteWorkingDate) <> 0 Then
           objRunningLogFile.WriteLine dteWorkingDate & ": No Backup Found!!"
           intFailedDays = intFailedDays + 1
           If DEBUGOUTPUT Then
              Wscript.Echo dteWorkingDate & ": No Backup Found!!"
           End If
        End If
        dteWorkingDate = DateAdd("d", -1, dteWorkingDate)
     End If
  Else
     On Error Resume Next
        objFSO.DeleteFile(objRS.Fields("Path"))
        If Err.Number = 0 Then
           intDeleteFilesCount = intDeleteFilesCount + 1
           
           objRunningLogFile.WriteLine objRS.Fields("Path") & " Deleted Successfully."
           If DEBUGOUTPUT Then 
              WScript.Echo objRS.Fields("Path") & " Deleted Successfully."
           End If
        Else
           objRunningLogFile.WriteLine objRS.Fields("Path") & " CANNOT BE DELETED!! Error was " &_
                                    CStr(Err.Number) & " " & Err.Description
           If DEBUGOUTPUT Then
              WScript.Echo objRS.Fields("Path") & " CANNOT BE DELETED!! Error was " &_
                        CStr(Err.Number) & " " & Err.Description
           End If
           Err.Clear
        End If
     On Error Goto 0
     
     objRS.MoveNext
  End If
Loop

objRunningLogFile.WriteLine vbCrLf & "Successful Days: " & intSuccessfulDays
objRunningLogFile.WriteLine "Failed Days: " & intFailedDays
objRunningLogFile.WriteLine "Deleted Files: " & intDeleteFilesCount
objRunningLogFile.Close
If DEBUGOUTPUT Then
  WScript.Echo vbCrLf & "Successful Days: " & intSuccessfulDays
  WScript.Echo "Failed Days: " & intFailedDays
  WScript.Echo "Deleted Files: " & intDeleteFilesCount
End If

' [b]Source[/b]: http://arstechnica.com/civis/viewtopic.php?p=21080024#p21080024

  • Thanks 2
Posted
One thing to keep in mind with your forfiles command is that it will delete the files regardless of whether there are new ones to take their place. For example, say there was an issue with your CCTV system and it didn't record anything for an entire week, you would end up with a completely empty Channel1 folder because all of the files are older than five days.

 

The VBScript below attempts to solve this problem by making sure that there are always five days worth of files kept, even if some of the files are actually older than five days (hopefully that makes sense?).

 

Option Explicit

CONST adFldIsNullable = &H00000020 
CONST adVarChar = 200 
CONST adDate = 7 
CONST adOpenDynamic = 2 
CONST adUseClient = 3 
Const ForReading = 1, ForWriting = 2, ForAppending = 8
' Set DEBUGOUTPUT to true to output to the console as well as logfile
CONST DEBUGOUTPUT = TRUE

Dim objFSO
Dim objFolder, colFiles, File
Dim objRunningLogFile
Dim objRS, intFailedDays, intSuccessfulDays, dteWorkingDate, dteNewestDate
Dim intDeleteFilesCount

' ******************************************************************************************
' Customization section:
'  strRunningLogFile will contain lists all last successful days, failed days, and deleted files
'  strTargetFolder is the location to scan for files, not recursive
'  DaysOfBackupsToKeep is # of days worth of data to store.  If the backups are weekly, set to 30 or more
' ******************************************************************************************
CONST strRunningLogFile = "[color="red"]C:\CCTV\RunningLog.txt[/color]"
CONST strTargetFolder = "[color="red"]C:\CCTV\Channel1[/color]"
CONST DayOfBackupsToKeep = [color="red"]5[/color]

Set objFSO = CreateObject("Scripting.FileSystemObject")  
Set objfolder = objFSO.GetFolder(strTargetFolder)

Set objRS = CreateObject("ADODB.Recordset")
With objRS
  .CursorLocation = adUseClient 
  .CursorType = adOpenDynamic
  .Fields.Append "Name", adVarChar, 255, adFldIsNullable
  .Fields.Append "Path", adVarChar, 255, adFldIsNullable
  .Fields.Append "DateMod", adDate, 32, adFldIsNullable
  .Open
End With

Set colFiles = objFolder.Files

For Each File in colFiles
  With objRS
     .AddNew
     .Fields("Name") = File.Name
     .Fields("Path") = File.Path
     .Fields("DateMod") = File.DateLastModified
     .Update
  End With
Next

objRS.Sort = "DateMod DESC"
If NOT objRS.EOF Then
  objRS.MoveFirst
End If

intFailedDays = 0
intSuccessfulDays = 0
intDeleteFilesCount = 0

dteWorkingDate = Date

Set objRunningLogFile = objFSO.OpenTextFile(strRunningLogFile, ForAppending, True)
objRunningLogFile.WriteLine vbCrLf & "------------------------------------------------------------------"
objRunningLogFile.WriteLine "Run time: " & Now
If DEBUGOUTPUT Then
  WScript.Echo "Report for " & strTargetFolder & " on " & Now
End IF
If NOT objRS.EOF Then
  objRunningLogFile.WriteLine "Most Recent Backup File dated: " & ObjRS.Fields("DateMod") & ", " &_
                              DateDiff("d", ObjRS.Fields("DateMod"), Date) & " day(s) ago."
  If DEBUGOUTPUT Then
     WScript.Echo "Most Recent Backup File dated: " & ObjRS.Fields("DateMod") & ", " &_
                   DateDiff("d", ObjRS.Fields("DateMod"), Date) & " day(s) ago."
  End If
End If

Do Until objRS.EOF
  If intSuccessfulDays < DayOfBackupsToKeep Then
     If DateDiff("d", objRS.Fields("DateMod"), dteWorkingDate) = 0 Then
        objRunningLogFile.WriteLine dteWorkingDate & ": " & vbTab & objRS.Fields("Name")
        If DEBUGOUTPUT Then
           WScript.Echo dteWorkingDate & ": " & vbTab & objRS.Fields("Name")
        End If
        intSuccessfulDays = intSuccessfulDays +1
        If intSuccessfulDays = 1 Then
           objRunningLogFile.WriteLine "Newest File: " & objRS.Fields("Name") & " - Modified: " & objRS.Fields("DateMod")
        End If
        objRS.MoveNext
        Do Until objRS.EOF
           If DateDiff("d", objRS.Fields("DateMod"), dteWorkingDate) = 0 Then
              objRunningLogFile.WriteLine vbTab & vbTab & objRS.Fields("Name")
              If DEBUGOUTPUT Then
                 Wscript.Echo vbTab & vbTab & objRS.Fields("Name")
              End If
              objRS.MoveNext
           Else
              dteWorkingDate = DateAdd("d", -1, dteWorkingDate)
              Exit Do
           End if
        Loop 
     Else
        If DateDiff("d", Date, dteWorkingDate) <> 0 Then
           objRunningLogFile.WriteLine dteWorkingDate & ": No Backup Found!!"
           intFailedDays = intFailedDays + 1
           If DEBUGOUTPUT Then
              Wscript.Echo dteWorkingDate & ": No Backup Found!!"
           End If
        End If
        dteWorkingDate = DateAdd("d", -1, dteWorkingDate)
     End If
  Else
     On Error Resume Next
        objFSO.DeleteFile(objRS.Fields("Path"))
        If Err.Number = 0 Then
           intDeleteFilesCount = intDeleteFilesCount + 1
           
           objRunningLogFile.WriteLine objRS.Fields("Path") & " Deleted Successfully."
           If DEBUGOUTPUT Then 
              WScript.Echo objRS.Fields("Path") & " Deleted Successfully."
           End If
        Else
           objRunningLogFile.WriteLine objRS.Fields("Path") & " CANNOT BE DELETED!! Error was " &_
                                    CStr(Err.Number) & " " & Err.Description
           If DEBUGOUTPUT Then
              WScript.Echo objRS.Fields("Path") & " CANNOT BE DELETED!! Error was " &_
                        CStr(Err.Number) & " " & Err.Description
           End If
           Err.Clear
        End If
     On Error Goto 0
     
     objRS.MoveNext
  End If
Loop

objRunningLogFile.WriteLine vbCrLf & "Successful Days: " & intSuccessfulDays
objRunningLogFile.WriteLine "Failed Days: " & intFailedDays
objRunningLogFile.WriteLine "Deleted Files: " & intDeleteFilesCount
objRunningLogFile.Close
If DEBUGOUTPUT Then
  WScript.Echo vbCrLf & "Successful Days: " & intSuccessfulDays
  WScript.Echo "Failed Days: " & intFailedDays
  WScript.Echo "Deleted Files: " & intDeleteFilesCount
End If

' [b]Source[/b]: http://arstechnica.com/civis/viewtopic.php?p=21080024#p21080024

 

You vbscript addict lol , only kidding. Beat me to it though, not been on edugeek very often or for long enough in the last few months or so.

  • Thanks 1
Posted
Just had a thought..... you do have forfiles.exe on your system?

 

EDIT:

 

If not you can download it from here: http://www.ipass.net/davesisk/oont_download_forfiles.htm

 

Tried it with this version and - same results as before.

 

 

One thing to keep in mind with your forfiles command is that it will delete the files regardless of whether there are new ones to take their place. For example, say there was an issue with your CCTV system and it didn't record anything for an entire week, you would end up with a completely empty Channel1 folder because all of the files are older than five days.

 

The VBScript below attempts to solve this problem by making sure that there are always five days worth of files kept, even if some of the files are actually older than five days (hopefully that makes sense?).

 

 

Code:

...

 

Tried that too and I get a windows popup like the one shown below as an attachment, for each file I've got in the folder (and there's 8109 - not good :p) and nothing happens after that.

I haven't changed anything within the script, was I supposed to? I had a look through and couldn't really see anything to change but then again I've not really had any experience with VBS.

I realised the filepath but that's fine.

 

Thanks again to all of you :)

errorscreener.JPG

Posted

Tried that too and I get a windows popup like the one shown below as an attachment, for each file I've got in the folder (and there's 8109 - not good :p) and nothing happens after that.

 

Ignore that - We have success - Although there was two popups for each file :/ the one shown above then one that was the same as that but it said "successfully deleted" at the end. I've linked a screenshot below. Now that script is brill, it does the job but is there anyway I can remove the popups? I assume it'll just be a matter of changing a 1 to a 0 or true to a false or something?

 

The problem is that the machine is only used for CCTV so if it needs accessing I don't want to have to sit through 10000+ popups from each time the script has run.

 

Those 8000 files I mentioned before was only from 10 days of recording!!

 

If Arthur does not reply I can have a look at this later on - I would use a different script that just does what you requested - although was thinking we could make it 6 days ??

 

If you have a script more suited to the task then I would be extremely greatful to see it, and yes, 6 days isn't a problem, I can just alter how often the script will be run.

Worked.JPG

Posted
Tried that too and I get a windows popup like the one shown below as an attachment, for each file I've got in the folder (and there's 8109 - not good :p) and nothing happens after that.

I forgot to mention that you need to run it using "cscript" to avoid those popups. One way to do this would be to create a batch file which in turn runs the VBScript.

 

cscript DeleteX.vbs

 

The log file should look something like this once it has been run...

 

------------------------------------------------------------------
Run time: 12/01/2011 08:17:19
Most Recent Backup File dated: 03/01/2011 00:17:01, 9 day(s) ago.
11/01/2011: No Backup Found!!
10/01/2011: No Backup Found!!
09/01/2011: No Backup Found!!
08/01/2011: No Backup Found!!
07/01/2011: No Backup Found!!
06/01/2011: No Backup Found!!
05/01/2011: No Backup Found!!
04/01/2011: No Backup Found!!
03/01/2011: 	example.wmv
Newest File: example.wmv - Modified: 03/01/2011 00:17:01
02/01/2011: No Backup Found!!
01/01/2011: No Backup Found!!
31/12/2010: No Backup Found!!
30/12/2010: No Backup Found!!
29/12/2010: No Backup Found!!
28/12/2010: No Backup Found!!
27/12/2010: No Backup Found!!
26/12/2010: No Backup Found!!
25/12/2010: 	example.swf
24/12/2010: No Backup Found!!
23/12/2010: No Backup Found!!
22/12/2010: No Backup Found!!
21/12/2010: No Backup Found!!
20/12/2010: No Backup Found!!
19/12/2010: No Backup Found!!
18/12/2010: No Backup Found!!
17/12/2010: 	example.mov
	example.iso
	example.mts
16/12/2010: No Backup Found!!
15/12/2010: No Backup Found!!
14/12/2010: 	example.avi
13/12/2010: No Backup Found!!
12/12/2010: No Backup Found!!
11/12/2010: No Backup Found!!
10/12/2010: No Backup Found!!
09/12/2010: No Backup Found!!
08/12/2010: No Backup Found!!
07/12/2010: 	example.mkv
C:\CCTV\Channel1\example.zip Deleted Successfully.
C:\CCTV\Channel1\example.rar Deleted Successfully.
C:\CCTV\Channel1\example.7z Deleted Successfully.
C:\CCTV\Channel1\example.dmg Deleted Successfully.
C:\CCTV\Channel1\example.cmd Deleted Successfully.
C:\CCTV\Channel1\example.tmp Deleted Successfully.

Successful Days: 5
Failed Days: 31
Deleted Files: 6

 

It worked perfectly when I tested it on my computer. :)

Posted (edited)

I have about 120 instances of that script running, strange it doesn't work for you.

 

EDIT: I also use forfiles /p d:\Folder /s /m *.* /d -1 /c "cmd /c move @FILE d:\Folder\archive"

Edited by creese
Posted
I forgot to mention that you need to run it using "cscript" to avoid those popups. One way to do this would be to create a batch file which in turn runs the VBScript.

 

cscript DeleteX.vbs

 

That works great, thanks :D

 

Although if anyone thinks they have a better script I'll be greatful for other suggestions, I've not had much experience with scripting so it's always good to get a bit of knowledge :)

 

I have about 120 instances of that script running, strange it doesn't work for you.

And yes that does seem strange, especially with how many other websites I've read with more or less the same script and people reporting it works fine too.

Posted (edited)

'=============
' Objective: To delete old files from a given folder and all subfolders below
' Created Date: June 27, 2007
' Usage: cscript deloldfiles.vbs c:\dba\log 3 partoffilename
'      : It deletes files older than 3 days
strInvalidUsage = "Usage: cscript deloldfiles.vbs BaseFolder DaysOld RecurseOn [FileName]" & VbCrLf &_
       "   BaseFolder:   REQUIRED   The full path to the target folder to delete from" & VbCrLf &_
       "   DaysOld:      REQUIRED   The minimum age in days of the files to delete" & VbCrLf &_
       "   RecurseOn:    REQUIRED   Value must be YES or NO" & VbCrLf &_
       "   FileName:     OPTIONAL   The name of the file(s) to delete.  An asterix (*)" & VbCrLf &_
       "                            wilcard can be placed at either end, or both ends" & VbCrLf &_
       "                            eg, *.txt   OR   file*   OR   *sample*" & VbCrLf & VbCrLf

If WScript.Arguments.Count <> 3 And WScript.Arguments.Count <> 4 Then
       WScript.Echo VbCrLf & "ERROR: Invalid amount of arguments." & VbCrLf
       WScript.Echo strInvalidUsage
       WScript.Quit
End If
Set objArgs = WScript.Arguments
FolderName =objArgs(0)
Days=objArgs(1)
RecurseOn = objArgs(2)
If RecurseOn <> "YES" And RecurseOn <> "NO" Then
       WScript.Echo VbCrLf & "ERROR: Invalid RecurseOn flag." & VbCrLf
       WScript.Echo strInvalidUsage
       WScript.Quit
End If
If WScript.Arguments.Count = 4 Then
     strPartOfFileName = objArgs(3)
Else
     strPartOfFileName = ""
End If

set fso = createobject("scripting.filesystemobject")
Set objFolder = fso.getfolder(FolderName)
datetoday = now()
newdate = dateadd("d", Days*-1, datetoday)
wscript.echo "Today:" & now()
wscript.echo "Started deleting files older than :" & newdate 
wscript.echo "________________________________________________"
wscript.echo ""

 set files = objFolder.files
'  wscript.echo ""
'  wscript.echo "Deleting Files under the Folder:" & objFolder.path
'  wscript.echo "__________________________________________________________________________"
 for each file in files
   if file.datelastmodified < newdate Then
           If strPartOfFileName <> "" Then
                 If Left(strPartOfFileName, 1) = "*" And Right(strPartOfFileName, 1) = "*" Then
                               'WScript.Echo "Looking for: " & LCase(Mid(strPartOfFileName, 2, Len(strPartOfFileName) - 2))
                       If InStr(LCase(file.Name), LCase(Mid(strPartOfFileName, 2, Len(strPartOfFileName) - 2))) > 0 Then
                             wscript.echo "Deleting " & objFolder.path & "\" & file.name & " last modified: " & file.datelastmodified
                             on error resume Next
                             'file.delete
                       End If
                 ElseIf Left(strPartOfFileName, 1) = "*" Then
                       If LCase(Right(file.Name, Len(strPartOfFileName) - 1)) = LCase(Right(strPartOfFileName, Len(strPartOfFileName) - 1)) Then
                             wscript.echo "Deleting " & objFolder.path & "\" & file.name & " last modified: " & file.datelastmodified
                             on error resume Next
                             'file.delete
                       End If                        
                 ElseIf Right(strPartOfFileName, 1) = "*" Then
                       If LCase(Left(file.Name, Len(strPartOfFileName) - 1)) = LCase(Left(strPartOfFileName, Len(strPartOfFileName) - 1)) Then
                             wscript.echo "Deleting " & objFolder.path & "\" & file.name & " last modified: " & file.datelastmodified
                             on error resume Next
                             'file.delete
                       End If                        
                 End If
           Else
                 wscript.echo "Deleting " & objFolder.path & "\" & file.name & " last modified: " & file.datelastmodified
                 on Error resume Next
                 'file.delete            
           End If
   end If
 Next
       
If UCase(RecurseOn) = "YES" Then
       recurse objFolder, strPartOfFileName
End If

wscript.echo ""
wscript.echo "Completed deleting files older than :" & newdate 
wscript.echo "________________________________________________"

sub recurse(folders, strPartOfFileName)
 For Each subfolder In folders.subfolders
 Set objFolder = fso.GetFolder(subfolder.Path)
 set files = objFolder.files
 wscript.echo ""
 wscript.echo "Deleting Files under the Folder:" & objFolder.path
 wscript.echo "__________________________________________________________________________"
 for each file in files
   if file.datelastmodified < newdate Then
           If strPartOfFileName <> "" Then
                 If Left(strPartOfFileName, 1) = "*" And Right(strPartOfFileName, 1) = "*" Then
                               'WScript.Echo "Looking for: " & LCase(Mid(strPartOfFileName, 2, Len(strPartOfFileName) - 2))
                       If InStr(LCase(file.Name), LCase(Mid(strPartOfFileName, 2, Len(strPartOfFileName) - 2))) > 0 Then
                             wscript.echo "Deleting " & objFolder.path & "\" & file.name & " last modified: " & file.datelastmodified
                             on error resume Next
                             'file.delete
                       End If
                 ElseIf Left(strPartOfFileName, 1) = "*" Then
                       If LCase(Right(file.Name, Len(strPartOfFileName) - 1)) = LCase(Right(strPartOfFileName, Len(strPartOfFileName) - 1)) Then
                             wscript.echo "Deleting " & objFolder.path & "\" & file.name & " last modified: " & file.datelastmodified
                             on error resume Next
                             'file.delete
                       End If                        
                 ElseIf Right(strPartOfFileName, 1) = "*" Then
                       If LCase(Left(file.Name, Len(strPartOfFileName) - 1)) = LCase(Left(strPartOfFileName, Len(strPartOfFileName) - 1)) Then
                             wscript.echo "Deleting " & objFolder.path & "\" & file.name & " last modified: " & file.datelastmodified
                             on error resume Next
                             'file.delete
                       End If                        
                 End If
           Else
                 wscript.echo "Deleting " & objFolder.path & "\" & file.name & " last modified: " & file.datelastmodified
                 on Error resume Next
                 'file.delete            
           End If
   end If
 Next
 'If UCase(RecurseOn) = "YES" Then
       recurse subfolder, strPartOfFileName
 'End If
 next  

 'for each folder in subfolders
 '  recurse folder, strPartOfFileName
 'next  

 'set subfolders = nothing
 'set files = nothing

end Sub

'=========

Try this for some wildcard usage. As an example, run this:

 

cscript "C:\Temp\DeleteOldFiles.vbs" C:\temp\temp 60 YES *wan*

pause

 

The 60 is the days old to delete, the YES means it will recurse subfolders, and the *wan* is the pattern to match.

 

Same as per Arthurs comment - use a batch file to run the 2 above relevant commands altering the first command to match your requirements ie how many days, the correct path where you want said files deleting from and also the YES or NO depending on if you want it to recurse sub folders and last but not least the pattern to match ( I presume this would be either the file name or the file type )

 

Also the file.Delete lines need un commenting, they have been commented out for testing purposes

 

 

Actually, looking at that, the recursion bit is commented out. Change this bit near the bottom:

Next

'If UCase(RecurseOn) = "YES" Then

recurse subfolder, strPartOfFileName

'End If

Next

 

to this

Next

If UCase(RecurseOn) = "YES" Then

recurse subfolder, strPartOfFileName

End If

Next

 

so that the recursion flag works.

 

You will also need to uncomment all of the

file.delete

lines when you actually want to delete them.

 

 

Original Code was from here :

 

http://www.experts-exchange.com/Programming/Languages/Visual_Basic/VB_Script/Q_23173209.html

Edited by mac_shinobi
  • Thanks 1
Posted
'=============
' Objective: To delete old files from a given folder and all subfolders below
' Created Date: June 27, 2007
' Usage: cscript deloldfiles.vbs c:\dba\log 3 partoffilename
'      : It deletes files older than 3 days
strInvalidUsage = "Usage: cscript deloldfiles.vbs BaseFolder DaysOld RecurseOn [FileName]" & VbCrLf &_
       "   BaseFolder:   REQUIRED   The full path to the target folder to delete from" & VbCrLf &_
       "   DaysOld:      REQUIRED   The minimum age in days of the files to delete" & VbCrLf &_
       "   RecurseOn:    REQUIRED   Value must be YES or NO" & VbCrLf &_
       "   FileName:     OPTIONAL   The name of the file(s) to delete.  An asterix (*)" & VbCrLf &_
       "                            wilcard can be placed at either end, or both ends" & VbCrLf &_
       "                            eg, *.txt   OR   file*   OR   *sample*" & VbCrLf & VbCrLf

If WScript.Arguments.Count <> 3 And WScript.Arguments.Count <> 4 Then
       WScript.Echo VbCrLf & "ERROR: Invalid amount of arguments." & VbCrLf
       WScript.Echo strInvalidUsage
       WScript.Quit
End If
Set objArgs = WScript.Arguments
FolderName =objArgs(0)
Days=objArgs(1)
RecurseOn = objArgs(2)
If RecurseOn <> "YES" And RecurseOn <> "NO" Then
       WScript.Echo VbCrLf & "ERROR: Invalid RecurseOn flag." & VbCrLf
       WScript.Echo strInvalidUsage
       WScript.Quit
End If
If WScript.Arguments.Count = 4 Then
     strPartOfFileName = objArgs(3)
Else
     strPartOfFileName = ""
End If

set fso = createobject("scripting.filesystemobject")
Set objFolder = fso.getfolder(FolderName)
datetoday = now()
newdate = dateadd("d", Days*-1, datetoday)
wscript.echo "Today:" & now()
wscript.echo "Started deleting files older than :" & newdate 
wscript.echo "________________________________________________"
wscript.echo ""

 set files = objFolder.files
'  wscript.echo ""
'  wscript.echo "Deleting Files under the Folder:" & objFolder.path
'  wscript.echo "__________________________________________________________________________"
 for each file in files
   if file.datelastmodified < newdate Then
           If strPartOfFileName <> "" Then
                 If Left(strPartOfFileName, 1) = "*" And Right(strPartOfFileName, 1) = "*" Then
                               'WScript.Echo "Looking for: " & LCase(Mid(strPartOfFileName, 2, Len(strPartOfFileName) - 2))
                       If InStr(LCase(file.Name), LCase(Mid(strPartOfFileName, 2, Len(strPartOfFileName) - 2))) > 0 Then
                             wscript.echo "Deleting " & objFolder.path & "\" & file.name & " last modified: " & file.datelastmodified
                             on error resume Next
                             'file.delete
                       End If
                 ElseIf Left(strPartOfFileName, 1) = "*" Then
                       If LCase(Right(file.Name, Len(strPartOfFileName) - 1)) = LCase(Right(strPartOfFileName, Len(strPartOfFileName) - 1)) Then
                             wscript.echo "Deleting " & objFolder.path & "\" & file.name & " last modified: " & file.datelastmodified
                             on error resume Next
                             'file.delete
                       End If                        
                 ElseIf Right(strPartOfFileName, 1) = "*" Then
                       If LCase(Left(file.Name, Len(strPartOfFileName) - 1)) = LCase(Left(strPartOfFileName, Len(strPartOfFileName) - 1)) Then
                             wscript.echo "Deleting " & objFolder.path & "\" & file.name & " last modified: " & file.datelastmodified
                             on error resume Next
                             'file.delete
                       End If                        
                 End If
           Else
                 wscript.echo "Deleting " & objFolder.path & "\" & file.name & " last modified: " & file.datelastmodified
                 on Error resume Next
                 'file.delete            
           End If
   end If
 Next
       
If UCase(RecurseOn) = "YES" Then
       recurse objFolder, strPartOfFileName
End If

wscript.echo ""
wscript.echo "Completed deleting files older than :" & newdate 
wscript.echo "________________________________________________"

sub recurse(folders, strPartOfFileName)
 For Each subfolder In folders.subfolders
 Set objFolder = fso.GetFolder(subfolder.Path)
 set files = objFolder.files
 wscript.echo ""
 wscript.echo "Deleting Files under the Folder:" & objFolder.path
 wscript.echo "__________________________________________________________________________"
 for each file in files
   if file.datelastmodified < newdate Then
           If strPartOfFileName <> "" Then
                 If Left(strPartOfFileName, 1) = "*" And Right(strPartOfFileName, 1) = "*" Then
                               'WScript.Echo "Looking for: " & LCase(Mid(strPartOfFileName, 2, Len(strPartOfFileName) - 2))
                       If InStr(LCase(file.Name), LCase(Mid(strPartOfFileName, 2, Len(strPartOfFileName) - 2))) > 0 Then
                             wscript.echo "Deleting " & objFolder.path & "\" & file.name & " last modified: " & file.datelastmodified
                             on error resume Next
                             'file.delete
                       End If
                 ElseIf Left(strPartOfFileName, 1) = "*" Then
                       If LCase(Right(file.Name, Len(strPartOfFileName) - 1)) = LCase(Right(strPartOfFileName, Len(strPartOfFileName) - 1)) Then
                             wscript.echo "Deleting " & objFolder.path & "\" & file.name & " last modified: " & file.datelastmodified
                             on error resume Next
                             'file.delete
                       End If                        
                 ElseIf Right(strPartOfFileName, 1) = "*" Then
                       If LCase(Left(file.Name, Len(strPartOfFileName) - 1)) = LCase(Left(strPartOfFileName, Len(strPartOfFileName) - 1)) Then
                             wscript.echo "Deleting " & objFolder.path & "\" & file.name & " last modified: " & file.datelastmodified
                             on error resume Next
                             'file.delete
                       End If                        
                 End If
           Else
                 wscript.echo "Deleting " & objFolder.path & "\" & file.name & " last modified: " & file.datelastmodified
                 on Error resume Next
                 'file.delete            
           End If
   end If
 Next
 'If UCase(RecurseOn) = "YES" Then
       recurse subfolder, strPartOfFileName
 'End If
 next  

 'for each folder in subfolders
 '  recurse folder, strPartOfFileName
 'next  

 'set subfolders = nothing
 'set files = nothing

end Sub

'=========

Try this for some wildcard usage. As an example, run this:

 

cscript "C:\Temp\DeleteOldFiles.vbs" C:\temp\temp 60 YES *wan*

pause

 

The 60 is the days old to delete, the YES means it will recurse subfolders, and the *wan* is the pattern to match.

 

Same as per Arthurs comment - use a batch file to run the 2 above relevant commands altering the first command to match your requirements ie how many days, the correct path where you want said files deleting from and also the YES or NO depending on if you want it to recurse sub folders and last but not least the pattern to match ( I presume this would be either the file name or the file type )

 

Also the file.Delete lines need un commenting, they have been commented out for testing purposes

 

 

 

Original Code was from here :

 

Script to delete files after X days : delete, vbscript, recursive, time

 

 

Thanks, I'll take a look at that one when I next get chance :)

Posted
You vbscript addict lol, only kidding.

I really like PowerShell now. :) Some things are so much simpler. e.g.

 

$a = Get-ChildItem C:\CCTV\Channel1 -recurse
foreach($x in $a)
{
   $y = ((Get-Date) - $x.CreationTime).Days
   if ($y -gt 5 -and $x.PsISContainer -ne $True)
       {$x.Delete()}
}

 

Source: http://blogs.technet.com/b/heyscriptingguy/archive/2007/10/31/hey-scripting-guy-how-can-i-use-windows-powershell-to-delete-all-the-files-in-a-folder-older-than-90-days.aspx

  • Thanks 2
Posted

@gtg

 

no problem - found that on a PAQ on EE and was better then what I was going to post

 

@ Arthur

 

Don't have as much time as I used to so syntax is a little confusing / defo different so I would have to sit down and go through it.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now



  • 43 When would you like EduGeek EDIT 2025 to be held?

    1. 1. Select a time period you can attend


      • I can make it in June\July
      • I can make it in August\Sept
      • Other time period. Comment below
      • Either time

×
×
  • Create New...