VB Script to delete old files fom the local and/or remote computer(s)

77180 pts.
IT Scripts
Windows management
We have many applications running on many different servers, which log their operations to text files. We learned how problematic this could be when one of our servers crashed because the hard disk was completely full.  Someone was supposed to be monitoring disk usage on this server, but that obviously didn't happen. Half of the hard disk was occupied by unuseful log files. This is a script I created to solve that problem.  It can be configured to delete old files on any number of machines, according to specific parameters for each one. It can be scheduled to run periodically on one central machine/server to delete files from all of your domain machines from there.  It must be run with an account with the appropriate privileges to execute the operation on the local and remote machines. -The Sysinternals' PsExec tool needs to exist on the local machine, because it is used to execute the delete command on the remote machines, since the Forfiles utility doesn't allow the use of UNC paths. -To delete the files it uses de Forfiles utility, which uses a different syntax depending on the Windows version.  This script uses the syntax from the Forfiles version included with Windows Server 2003 and above, so it will probably not work to delete files on XP machines without some small modification. Explanations about its usage are included in the code below.
'    This script will delete old files from the local and/or remote computer(s)
'        according to the parameters defined in the initialization file,
'        whose name must be passed as a command line argument to execute the script.
'    The ini file must define the path, pattern and age of the files that have
'        to be deleted, and must specify whether the script has to recurse into
'        subdirectories to delete files.
'    The ini file can define any number of computers, using the machine name or ip address.
'    To be able to work on remote computers, the PsExec tool from Sysinternals needs to exist
'        on the local machine.
'    This script must be run using an account with the appropriate privileges to execute
'        remote commands using Sysinternals' PsExec.
'    Here's an example of the ini file
'Recursive = yes
'Path=c:supports paths with spaces
'Pattern = *.*
'    The machine name or ip address must be enclosed in brackets [...].
'        Use "local" to define an entry for the local machine.
'    The first machine entry must include all 4 parameters (Path,Pattern,Recursive,Days)
'        From the second machine onwards, if a parameter is not defined the value
'            used for the previous machine will be used, so If the parameters
'            are the same for all of the machines, you just need to define them
'            in the first entry.
'    The script will delete files that are at least <DAYS> days old, whose name matches
'        the defined pattern.
'    *** This script is provided AS IS without warranty of any kind
'       *** The author is not liable for anything that results from your use of this code
' Author: Carlos De Leon - 2011

Const ForReading = 1
If Wscript.Arguments.count <> 1 then
    MsgBox "Wrong number of parameters.  Usage DeleteOldFiles.vbs <parameter file name>"
End if
strFile = Wscript.Arguments(0)

Set objFSO = CreateObject("Scripting.FileSystemObject")
if objFSO.fileexists (strFile) then
    'Opening ini file
    Set objTextFile = objFSO.OpenTextFile (strFile, ForReading)
    Set wshShell = WScript.CreateObject ("WSCript.shell")
    booRead = True
    Do While not objTextFile.AtEndOfStream
            if booRead then
            strTextLine = objTextFile.Readline
        end if
           'ignore blank lines
        if len(trim(strTextLine)) > 0 then
            'Every entry must start with "["
            if left(strTextLine,1) = "[" then
                'Extracts the machine name
                strMachine = mid(strTextLine,2,len(strTextLine)-2)
                'Reads current machine's parameters
                intLine = 0
                Do while intLine <= 3 and not objTextFile.AtEndOfStream
                    strTextLine = ""
                    Do while trim(strTextLine) = "" and not objTextFile.AtEndOfStream
                        strTextLine = objTextFile.Readline 
                    If left(strTextLine,1) = "[" then
                        'Reached the next machine's entry
                        booRead = False
                        Exit do
                    end if
                    intLine = intLine + 1
                    strParameter = ucase(trim(left(strTextLine,instr(strTextLine,"=")-1)))
                    Select case strParameter                    
                    Case "PATH" 
                        'Adds quotes to be able to handle paths with blank spaces
                        strPath = trim(mid(strTextLine,instr(strTextLine,"=")+1,len(strTextLine)))
                        if right(strPath,1) = "" then
                            strPath = left(strPath,len(strPath)-1)
                        end if
                        strPath = """" + strPath + """"
                    Case "PATTERN"
                        strPattern = trim(mid(strTextLine,instr(strTextLine,"=")+1,len(strTextLine)))
                    Case "DAYS"
                        strDays = trim(mid(strTextLine,instr(strTextLine,"=")+1,len(strTextLine)))
                    Case "RECURSIVE"
                        strRecursive = trim(mid(strTextLine,instr(strTextLine,"=")+1,len(strTextLine)))
                    Case else
                        msgbox "Invalid parameter found for machine """ + strMachine + """"
                    End Select
                'Constructs the commands, using psExec for remote machines
                strS = " "
                If UCase(strRecursive) = "YES" then
                    strS = " /s"
                End if
                If strPath = "" or strPattern = "" or strDays = "" then
                    msgbox "At least one parameter is missing for machine """ + strMachine + """"
                end if
                strSubcommand = "forfiles /p " + strPath + strS + " /m " + strPattern + " /d -" + strDays + " /c ""cmd /c del @file"""
                if UCase(strMachine) = "LOCAL" then
                    strCommand = strSubcommand
                    strCommand = "psExec -i \" + strMachine + " " + strSubCommand
                end if
                'Executes the command
                wshshell.run strCommand, 6, True
            end if

        end if
    msgbox "Initialization file """ + Wscript.Arguments(0) + """ was not found"
end if

set wshshell = nothing
As always, please test it before attempting to run it on a production environment. If you have any comments or doubts or if you want to provide some feedback, please post it in the discussion section below. (Just in case:  This is not a question, I'm just sharing this script in case someone finds it useful)

Software/Hardware used:
Microsoft Windows, VB Script

Answer Wiki

Thanks. We'll let you know when a new response is added.
Send me notifications when members answer or reply to this question.

Discuss This Question: 2  Replies

There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when members answer or reply to this question.
  • carlosdl
    BTW, the editor seems to act different when editing a question. Backslashes need to be escaped when creating the question, but they don't need to be escaped when editing it.
    77,180 pointsBadges:
  • Announcing the winners of the IT Scripts Contest - ITKE Community Blog
    [...] pointed to scripts he’d previously posted to help others out. Carlos actually posted several really useful scripts, making it hard to pick one, which is why we [...]
    0 pointsBadges:

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

To follow this tag...

There was an error processing your information. Please try again later.

Thanks! We'll email you when relevant content is added and updated.


Share this item with your network: