Solved

remove contents of a file path older than 30 days.

Posted on 2013-05-23
12
577 Views
Last Modified: 2013-06-10
We need help to put together a batch script to navigate to a folder c:\abc\logs and remove any contents (directories or files) with modified date older than 30 days.  

Please advise.

Thanks.
0
Comment
Question by:nav2567
  • 5
  • 4
  • 2
  • +1
12 Comments
 
LVL 8

Accepted Solution

by:
jpgobert earned 133 total points
ID: 39191394
What's your OS version?

Forfiles is the easiest way to do this.  See below:

Microsoft Windows [Version 6.2.9200]
(c) 2012 Microsoft Corporation. All rights reserved.

C:\Users\xxxx>forfiles /?

FORFILES [/P pathname] [/M searchmask] [/S]
         [/C command] [/D [+ | -] {MM/dd/yyyy | dd}]

Description:
    Selects a file (or set of files) and executes a
    command on that file. This is helpful for batch jobs.

Parameter List:
    /P    pathname      Indicates the path to start searching.
                        The default folder is the current working
                        directory (.).

    /M    searchmask    Searches files according to a searchmask.
                        The default searchmask is '*' .

    /S                  Instructs forfiles to recurse into
                        subdirectories. Like "DIR /S".

    /C    command       Indicates the command to execute for each file.
                        Command strings should be wrapped in double
                        quotes.

                        The default command is "cmd /c echo @file".

                        The following variables can be used in the
                        command string:
                        @file    - returns the name of the file.
                        @fname   - returns the file name without
                                   extension.
                        @ext     - returns only the extension of the
                                   file.
                        @path    - returns the full path of the file.
                        @relpath - returns the relative path of the
                                   file.
                        @isdir   - returns "TRUE" if a file type is
                                   a directory, and "FALSE" for files.
                        @fsize   - returns the size of the file in
                                   bytes.
                        @fdate   - returns the last modified date of the
                                   file.
                        @ftime   - returns the last modified time of the
                                   file.

                        To include special characters in the command
                        line, use the hexadecimal code for the character
                        in 0xHH format (ex. 0x09 for tab). Internal
                        CMD.exe commands should be preceded with
                        "cmd /c".

    /D    date          Selects files with a last modified date greater
                        than or equal to (+), or less than or equal to
                        (-), the specified date using the
                        "MM/dd/yyyy" format; or selects files with a
                        last modified date greater than or equal to (+)
                        the current date plus "dd" days, or less than or
                        equal to (-) the current date minus "dd" days. A
                        valid "dd" number of days can be any number in
                        the range of 0 - 32768.
                        "+" is taken as default sign if not specified.

    /?                  Displays this help message.

Examples:
    FORFILES /?
    FORFILES
    FORFILES /P C:\WINDOWS /S /M DNS*.*
    FORFILES /S /M *.txt /C "cmd /c type @file | more"
    FORFILES /P C:\ /S /M *.bat
    FORFILES /D -30 /M *.exe
             /C "cmd /c echo @path 0x09 was changed 30 days ago"
    FORFILES /D 01/01/2001
             /C "cmd /c echo @fname is new since Jan 1st 2001"
    FORFILES /D +5/23/2013 /C "cmd /c echo @fname is new today"
    FORFILES /M *.exe /D +1
    FORFILES /S /M *.doc /C "cmd /c echo @fsize"
    FORFILES /M *.txt /C "cmd /c if @isdir==FALSE notepad.exe @file"

C:\Users\xxxx>
0
 
LVL 7

Assisted Solution

by:BT15
BT15 earned 100 total points
ID: 39191409
can you use powershell?


Get-ChildItem c:\abc\logs -recurse | ? {$_.lastwritetime -lt (get-date).adddays(-30)} \ % {del $_.fullname}
0
 
LVL 8

Expert Comment

by:jpgobert
ID: 39191419
The following should do the trick... just adjust the maxage variable and pathtoclean to match the path you want.

@echo off
:: set cleanup path
set pathtoclean=c:\abc\logs
 
:: set the max age in days
set maxage=30
 
:: remove files from %pathtoclean%
forfiles -p %pathtoclean% -m *.* -d -%maxage% -c "cmd  /c del /q @path"
 
:: clean up subfolders %pathtoclean%
forfiles -p %pathtoclean% -d -%maxage% -c "cmd /c IF @isdir == TRUE rd /S /Q @path"

Open in new window

0
 
LVL 51

Assisted Solution

by:Bill Prew
Bill Prew earned 267 total points
ID: 39191528
Here's a VBS script I use from time to time, adjust the settings near the top and the folder(s) you want to purge.

' 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
 

Author Comment

by:nav2567
ID: 39191952
jbgobert, would you modify your script to delete folders starting with 2 only?

There are a lot of subfolders we want to remove start with 20130101, 20130102......

Thanks everyone.
0
 
LVL 8

Expert Comment

by:jpgobert
ID: 39192115
Are these subfolders under the path C:\abc\logs ?

Examples:  
c:\abc\logs\20130101
c:\abc\logs\20130102

If so, you still want to delete the contents and the folder itself, correct?  Are there any additional subfolders under the date-named folders?

Let me know and I'll post an update shortly.
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 

Author Comment

by:nav2567
ID: 39192267
That's correct.  The c:\abc\logs folder has a lot of subfolders starting with 2013........

The thing is there are other system folders in c:\abc\logs which we do not want to touch and exclude those.

Thanks.
0
 
LVL 8

Expert Comment

by:jpgobert
ID: 39192543
Here's the update.  If you look at line 9 you'll see %pathtoclean%2* in the FOR loop's filter.  The 2* causes only folders starting with 2 should be included.  If you wanted to expand that to be 2013 then it would be %pathtoclean%2013*.  Make sense?

@echo off

:: set cleanup path
set pathtoclean=C:\abc\logs\
 
:: set the max age in days
set maxage=30

FOR /F %%i in ('DIR /b /ad %pathtoclean%2*') DO SET FOLDER_NAME=%%i & CALL :SUB_CLEANUP %FOLDER_NAME%

:SUB_CLEANUP

SET FULL_PATH = %pathtoclean%%FOLDER_NAME%
FORFILES /P %FULL_PATH% /M *.* /D -%maxage% /C "CMD /C ECHO Y | DEL @PATH")
FORFILES /P %FULL_PATH% /D -%maxage% /C "CMD /C IF @isdir == TRUE RMDIR /S /Q @PATH")

Open in new window

0
 

Author Comment

by:nav2567
ID: 39192612
No good.  I am seeing this when I run:

File Not Found
ERROR: Invalid syntax. Value expected for '/P'.
Type "FORFILES /?" for usage.
ERROR: Invalid syntax. Value expected for '/P'.
Type "FORFILES /?" for usage.
Press any key to continue . . .
0
 
LVL 8

Expert Comment

by:jpgobert
ID: 39192785
What's the OS you're running this on?
0
 
LVL 51

Assisted Solution

by:Bill Prew
Bill Prew earned 267 total points
ID: 39193059
So, just to make sure I understand.  There are both files and folders under "c:\abc\logs".  

If those files have not been modified based on the last modified date in 30 days, then delete them.

If those folders have not been modified based on the last modified date in 30 days, then delete them.

Do you ever want to look at the files or folders within the first level of subfolders? So say, there is a subfolder that has been changed in 30 days, but has some old files in it, do you want to remove just those?  Or is it all or nothing with the subfolder?

Do you only want a BAT solution, or would VBS be acceptable?

~bp
0
 

Author Closing Comment

by:nav2567
ID: 39236512
Thanks everyone.  JPRobert's script works best in our environment.  Thanks again.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Introduction During my participation as a VBScript contributor at Experts Exchange, one of the most common questions I come across is this: "I have a script that runs against only one computer. How can I make it run against a list of computers in …
Deploying a Microsoft Access application in a Citrix environment is not difficult but takes a few steps. However, Citrix system people are often of little help, as they typically know next to nothing about Access. The script provided here will take …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

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