Solved

vbs script to delete folders/files which are present for more than 30 days

Posted on 2014-09-12
18
263 Views
Last Modified: 2014-10-01
We have log files which occur daily in the format c:\test\yyyy\mm\dd date format in one of our systems

However, I need to delete previous months folders/files so the most recent files/folders are present

Thanks
0
Comment
Question by:rakkad
18 Comments
 
LVL 4

Expert Comment

by:Saschao
ID: 40320261
Hi, here is some script I am using, just translated from german:

this is removing all zip files older than 6 days from this d:\backup folder.

--
    Option Explicit
    Dim intNumber
    Dim strExtension
    Dim intDays
    Dim objFile
    Dim objFSO
    Dim objFolder
    Dim strFolder
     
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    strFolder = "D:\Backup\"
    strExtension = "zip"
    intDays = 6
     
    Set objFolder = objFSO.GetFolder(strFolder)
    intNumber = 0
    For Each objFile In objFolder.Files
        If LCase(Right(objFile.name, Len(strExtension))) = LCase(strExtension) _
            And DateDiff("d", objFile.DateLastModified, Now) > intDays Then
            objFile.Delete
            intNumber = intNumber + 1
        End If
    Next

Open in new window

--

Sascha
0
 
LVL 51

Expert Comment

by:Bill Prew
ID: 40320416
So, do you want to delete all days and the month folder where the month is less than the current month?

Or do you need to keep say exactly 30 days of folders, and delete back from there?

~bp
0
 
LVL 24

Expert Comment

by:Mohammed Khawaja
ID: 40320485
You don't need a VBScript, you could use forfiles command.  The command could be as simple as below:

forfiles -p "C:\what\ever" -s -m *.* -d 30 -c "cmd /c del @path"
0
 

Author Comment

by:rakkad
ID: 40320622
~bp

Yes I want to delete all files where the month is less than the current month

Thanks
0
 
LVL 51

Expert Comment

by:Bill Prew
ID: 40321344
Here's a BAT script approach, which does what you described.  Run it from the command prompt.  Currently the RD command will just ECHO to the screen to allow testing so you can validate it works.  If the folders shown look right then remove the word ECHO before the RD command and run for real.

Keep in mind all days folders and files in that month folder will be removed.

@echo off
setlocal EnableDelayedExpansion

REM Define base folder for log folders
set BaseDir=B:\EE\EE28517538\test

REM Get current Month in YYYYMM format
set CurrentMonth=%DATE:~-4%%DATE:~-10,2%
set CurrentMonth=%CurrentMonth: =0%

REM Get month folders, and if older than current month remove them
for /d %%Y in ("%BaseDir%\????") do (
  set YYYY=%%~nY
  for /d %%M in ("%%~Y\??") do (
    set FolderMonth=%%~nY%%~nM
    if !FolderMonth! LSS %CurrentMonth% (
      ECHO rd /q /s "%%~M"
    )
  )
)

Open in new window

~bp
0
 

Author Comment

by:rakkad
ID: 40322056
Thanks ~bp

Do you have this as a vbscript format
Can you describe how the script works ?

Thanks
0
 
LVL 51

Accepted Solution

by:
Bill Prew earned 500 total points
ID: 40322993
Here is a VBS version. I commented clearly to explain what it is doing.  Currently the actual DeleteFolder() calls are commented out, so it will just display the folders it would delete to the screen.  Give it some testing and if it looks good uncomment those lines.

' Specify base location to purge old backups from
' Folders to purge should be subfolders under this one with YYYY\MM\DD format names
sBaseDir = "B:\EE\EE28517538\test"

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

' Get todays year and month for checks below
iCurrentYear = Year(Date)
iCurrentMonth = Month(Date)

' Process the first level folders under the base folder
For Each oYearFolder In oFSO.GetFolder(sBaseDir).SubFolders
   ' Make sure the folder name is YYYY (length of 4 and numeric)
   If Len(oYearFolder.Name) = 4 And IsNumeric(oYearFolder.Name) Then
      ' If the year of these backups is older than current year, remove them 
      If Cint(oYearFolder.Name) < iCurrentYear Then
         Wscript.Echo "Removing year folder: " & oYearFolder.Path
         ' oFSO.DeleteFolder(oYearFolder.Path)
      End If
      ' If the year of these backups is same as current year, need to check month subfolders
      If Cint(oYearFolder.Name) = iCurrentYear Then
         For Each oMonthFolder In oYearFolder.SubFolders
            ' Make sure the folder name is MM (length of 2 and numeric)
            If Len(oMonthFolder.Name) = 2 And IsNumeric(oMonthFolder.Name) Then
               ' If the month of these backups is older than current month, remove them 
               If Cint(oMonthFolder.Name) < iCurrentMonth Then
                  Wscript.Echo "Removing month folder: " & oMonthFolder.Path
                  ' oFSO.DeleteFolder(oMonthFolder.Path)
               End If
            End If
         Next
      End If
   End If
Next

Open in new window

~bp
0
 

Author Comment

by:rakkad
ID: 40331486
the vbscript works brilliant, I would like to include some error trapping, i.e. if the code fails can you include any error trapping messages

Thanks
0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 

Author Comment

by:rakkad
ID: 40331513
I need to modify the script yet again, so... in addition to removing the month folder which is not the current month, I would also like to remove dd folders within the current month so the most recent dd folder is present

thanks once again.. :-)
0
 
LVL 51

Assisted Solution

by:Bill Prew
Bill Prew earned 500 total points
ID: 40343132
Give this a try to handle the day folders before the current day.

' Specify base location to purge old backups from
' Folders to purge should be subfolders under this one with YYYY\MM\DD format names
sBaseDir = "B:\EE\EE28517538\test"

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

' Get todays year and month for checks below
iCurrentYear = Year(Date)
iCurrentMonth = Month(Date)
iCurrentDay = Day(Date)

' Process the first level folders under the base folder
For Each oYearFolder In oFSO.GetFolder(sBaseDir).SubFolders
   ' Make sure the folder name is YYYY (length of 4 and numeric)
   If Len(oYearFolder.Name) = 4 And IsNumeric(oYearFolder.Name) Then
      ' If the year of these backups is older than current year, remove them 
      If Cint(oYearFolder.Name) < iCurrentYear Then
         Wscript.Echo "Removing year folder: " & oYearFolder.Path
         ' oFSO.DeleteFolder(oYearFolder.Path)
      End If
      ' If the year of these backups is same as current year, need to check month subfolders
      If Cint(oYearFolder.Name) = iCurrentYear Then
         For Each oMonthFolder In oYearFolder.SubFolders
            ' Make sure the folder name is MM (length of 2 and numeric)
            If Len(oMonthFolder.Name) = 2 And IsNumeric(oMonthFolder.Name) Then
               ' If the month of these backups is older than current month, remove them 
               If Cint(oMonthFolder.Name) < iCurrentMonth Then
                  Wscript.Echo "Removing month folder: " & oMonthFolder.Path
                  ' oFSO.DeleteFolder(oMonthFolder.Path)
               End If
              ' If the month of these backups is same as current month, need to check day subfolders
               If Cint(oMonthFolder.Name) = iCurrentMonth Then
                  For Each oDayFolder In oMonthFolder.SubFolders
                     ' Make sure the folder name is DD (length of 2 and numeric)
                     If Len(oDayFolder.Name) = 2 And IsNumeric(oDayFolder.Name) Then
                        ' If the day of these backups is older than current day, remove them 
                        If Cint(oDayFolder.Name) < iCurrentDay Then
                           Wscript.Echo "Removing day folder: " & oDayFolder.Path
                           ' oFSO.DeleteFolder(oDayFolder.Path)
                        End If
                     End If
                  Next
               End If
            End If
         Next
      End If
   End If
Next

Open in new window

~bp
0
 

Author Comment

by:rakkad
ID: 40345595
Hi ~bp

I would like to include some error trapping, i.e. if the code fails can you include any error trapping messages

Thanks
0
 
LVL 51

Expert Comment

by:Bill Prew
ID: 40351386
What types of errors do you want to trap for?

~bp
0
 

Author Comment

by:rakkad
ID: 40351533
say if the script fails ?
0
 
LVL 51

Expert Comment

by:Bill Prew
ID: 40352842
Well, if the script itself fails, this it would not be able to trap that condition, you would have to trap that in whatever launched the script initially.

~bp
0
 

Author Comment

by:rakkad
ID: 40355398
Or can you include a log file to indicate which files have been removed ?

Thanks
0
 
LVL 51

Expert Comment

by:Bill Prew
ID: 40356174
Simple way to get that (since I was already writing the folders removed to standard output) would be to send the output from the script to a file when you run it, something like this:

cscript //nologo yourscript.vbs >c:\logs\yourscript.txt

~bp
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Welcome to part one of a multi-part tutorial series, VBScript for Windows System Administrators.  The goal of this series is to teach non-programmers how to write useful VBS code to automate their environment, and perform tasks faster, and in a more…
Welcome back!  My apologies for taking so long to write part two of this series; it's been a long time coming!  As I promised in Part 1, this article will focus on how to locate those elusive AD properties that you are searching for.  Why is this us…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

706 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

19 Experts available now in Live!

Get 1:1 Help Now