Announcement

Collapse
No announcement yet.

Deleting Temp Files in User Profiles with VBS

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Deleting Temp Files in User Profiles with VBS

    Good day all,

    Just wondering... well to be honest it's bound to be possible - I just don't know how complex...

    Anyway, back to the question at hand... basically I'd like to have a vbs script that will enable me to clear out temporary files in a user profile based on date...

    e.g. everything in: c:\documents and settings\user\local settings\temporary internet files\ and everything in c:\documents and settings\user\local settings\temp that's over x days old...

    I have been given one that deletes files in c:\winxppro\temp over 20 days old by a friend (but its probably floating around the internet) - see below:

    Code:
    ' ***************************************************
    ' * This script will delete all files in a folder and
    ' * sub-folder where when files are x number of days
    ' * old.
    ' *
    ' * Files will be deleted and not retained in the 
    ' * recycle bin.
    ' *
    ' * Alter the path and lifetime variables to your needs
    
    ' * Alter this variable, this is the starting point
    ' * for the deletion.
    ' * Example : path = "\\teacher\backup" 
    ' * Example : path = "N:\Logfiles" 
    
    Path = "C:\WINXPPro\TEMP" 
    
    ' * Alter this variable, if sub-folders should be processed
    ' * Process Sub folders Example : Subfolders = True 
    ' * Process Sub folders Example : Subfolders = False 
    
    Subfolders = False
    ' * Alter this variable to set the how many days old
    ' * the file should be before it is deleted.
    
    ' * Example : lifetime = date() - 20
    ' *           Will delete files that are 20 days old or more
    
    Lifetime = date() - 20 
    
    ' *******************************************************
    ' Script starts at this point
    ' *******************************************************
    ' Declare a variable as an Array that will store a listing
    ' of files that will be checked.
    
    FilesArray = Array() 
    
    ' Create an instance of the FileSystemObject so that file
    ' information can be obtained.
    
    set fso = createobject("scripting.filesystemobject") 
    
    ' Call the SelectFiles procedure to Fill the array with 
    ' files and folders that will be deleted
    
    SelectFiles path, lifetime, FilesArray, Subfolders
    
    ' Process the FilesArray deleting files as we loop through
    
    numDeleted = 0 
    
    for n = 0 to ubound(FilesArray)
        ' Switch off error checking, so that errors are ignored
        on error resume next
        ' Call the delete function to delete the selected file
        FilesArray(n).delete true 
        ' Handle any errors or results.  This could be modified
        ' to log to a text file.
        'if err.number <> 0 then 
        '    wscript.echo "Unable to delete: " & FilesArray(n).path 
        'else 
        '    numDeleted = numDeleted + 1 
        'end if 
        ' Switch Error checking back to normal
        on error goto 0 
    next 
    
    sub SelectFiles(sPath,vlifetime,FilesArrayToKill,bIncludeSubFolders) 
        ' Switch off Error handling, errors ignored.
        on error resume next 
        'select files to delete and add to array... 
        set folder = fso.getfolder(sPath) 
        set files  = folder.files 
    
        ' Loop through files that have been found
        for each file in files 
            ' uses error trapping around access to the 
            ' Date property just to be safe 
    
            dtlastmodified = null
            on error resume Next 
            dtlastmodified = file.datelastmodified 
            on error goto 0 
    
            if not isnull(dtlastmodified) Then 
                if dtlastmodified < vlifetime then 
                    count = ubound(FilesArrayToKill) + 1 
                    redim preserve FilesArrayToKill(count) 
                    set FilesArrayToKill(count) = file 
                end if 
            end if 
        next 
    
        ' If sub-folders are selected, call the procedure again to update
        ' the array with the contents.
    
        if bIncludeSubFolders then 
            for each fldr in folder.subfolders 
                SelectFiles fldr.path,vlifetime,FilesArrayToKill,true 
            next 
        end if 
    end sub
    To be perfectly honest I'm not hugely familar with half the things in there but am trying to go through and understand it...

    After its deleted all those I'd like it to also report back to say what its deleted - a log file or msgbox... I imagine it'd be a huge amount so probably a log file would be best.


    so... any takers?
    This is my signature.

  • #2
    Re: Deleting Temp Files in User Profiles with VBS

    I think I changed it correctly. Read the comments. It pretty much already had the functionality you were looking for. I just added the log file bit and un-commented a few lines.

    I should note that I haven't tested this script.

    Code:
    ' ***************************************************
    ' * This script will delete all files in a folder and
    ' * sub-folder where when files are x number of days
    ' * old.
    ' *
    ' * Files will be deleted and not retained in the 
    ' * recycle bin.
    ' *
    ' * Alter the path and lifetime variables to your needs
    ' * Alter this variable, this is the starting point
    ' * for the deletion.
    ' * Example : path = "\\teacher\backup" 
    ' * Example : path = "N:\Logfiles" 
    
    Path = "C:\WINXPPro\TEMP" 
    
    ' * Alter this variable, if sub-folders should be processed
    ' * Process Sub folders Example : Subfolders = True 
    ' * Process Sub folders Example : Subfolders = False 
    
    Subfolders = False
    
    ' * Alter this variable to set the how many days old
    ' * the file should be before it is deleted.
    ' * Example : lifetime = date() - 20
    ' *           Will delete files that are 20 days old or more
    
    Lifetime = date() - 20 
    
    ' * Change the path to where the log file is.
    ' * Be sure the text file already exists or else 
    ' * script will fail.
    strLogFile = "c:\logs\fileDeleteLog.txt"
    
    ' *******************************************************
    ' Script starts at this point
    ' *******************************************************
    ' Declare a variable as an Array that will store a listing
    ' of files that will be checked.
    
    FilesArray = Array() 
    
    ' Create an instance of the FileSystemObject so that file
    ' information can be obtained.
    
    set fso = createobject("scripting.filesystemobject") 
    
    ' Call the SelectFiles procedure to Fill the array with 
    ' files and folders that will be deleted
    
    SelectFiles path, lifetime, FilesArray, Subfolders
    
    ' Process the FilesArray deleting files as we loop through
    
    numDeleted = 0 
    
    for n = 0 to ubound(FilesArray)
        ' Switch off error checking, so that errors are ignored
        on error resume next
        ' Call the delete function to delete the selected file
        FilesArray(n).delete true 
        ' Handle any errors or results.  This could be modified
        ' to log to a text file.
        if err.number <> 0 then 
            Set objFile = FSO.OpenTextFile(strLogFile, 8) 
            objFile.WriteLine Now & vbTab & "ERROR - Unable to delete: " & FilesArray(n).path
            objFile.Close
        else 
            numDeleted = numDeleted + 1
            Set objFile = FSO.OpenTextFile(strLogFile, 8) 
            objFile.WriteLine Now & vbTab & "Deleted: " & FilesArray(n).path
            objFile.Close
     
        end if 
        ' Switch Error checking back to normal
        on error goto 0 
    next 
    
    Set objFile = FSO.OpenTextFile(strLogFile, 8) 
    objFile.WriteBlankLines(1)
    objFile.WriteLine "Total Files and Folders Deleted: " & numDeleted
    objFile.WriteBlankLines(4)
    objFile.Close
    
    sub SelectFiles(sPath,vlifetime,FilesArrayToKill,bIncludeSubFolders) 
        ' Switch off Error handling, errors ignored.
        on error resume next 
        'select files to delete and add to array... 
        set folder = fso.getfolder(sPath) 
        set files  = folder.files 
    
        ' Loop through files that have been found
        for each file in files 
            ' uses error trapping around access to the 
            ' Date property just to be safe 
    
            dtlastmodified = null
            on error resume Next 
            dtlastmodified = file.datelastmodified 
            on error goto 0 
    
            if not isnull(dtlastmodified) Then 
                if dtlastmodified < vlifetime then 
                    count = ubound(FilesArrayToKill) + 1 
                    redim preserve FilesArrayToKill(count) 
                    set FilesArrayToKill(count) = file 
                end if 
            end if 
        next 
    
        ' If sub-folders are selected, call the procedure again to update
        ' the array with the contents.
    
        if bIncludeSubFolders then 
            for each fldr in folder.subfolders 
                SelectFiles fldr.path,vlifetime,FilesArrayToKill,true 
            next 
        end if 
    end sub
    My changes I highlighted in red.
    In the script I made a note about needing the file to exists before hand but code can be added to handle that pretty easily... I just want to go to bed right now though
    Regards,
    Jeremy

    Network Consultant/Engineer
    Baltimore - Washington area and beyond
    www.gma-cpa.com

    Comment


    • #3
      Re: Deleting Temp Files in User Profiles with VBS

      That seems to work - as you mentioned you need to have the c:\logs\fileDeleteLog.txt file existing... - it also just reports how many were deleted... is there any way to get it to output the file path - i.e.
      c:\WinxpPro\temp\fred.txt
      c:\WinxpPro\temp\test.txt

      Total files deleted: 2
      It doesn't delete folders though... is it possible to add in somewhere to delete folders too?

      Also if the files/folders are in use will it still try to delete them? fail the script? or just leave them alone... as I'd be trying to delete some temporary files in a profile chances are a small percentage might be in use...

      also I guess if I wanted to specify a user path I can just add in a prompt box for a variable - enter the username and away it goes...
      This is my signature.

      Comment


      • #4
        Re: Deleting Temp Files in User Profiles with VBS

        I had a logical error (correction highlighted in red) in the script and that's why the reporting wasn't working. I tried to retrieve the path after the file was already deleted.

        I also added the subfolder deletion. Right now, if you have it search subfolders, it will also delete them provided the modify date is old enough. If you want, we can make it so that you can choose whether to delete them or not. (addition highlighted in blue)

        Code:
        ' ***************************************************
        ' * This script will delete all files in a folder and
        ' * sub-folder where when files are x number of days
        ' * old.
        ' *
        ' * Files will be deleted and not retained in the 
        ' * recycle bin.
        ' *
        ' * Alter the path and lifetime variables to your needs
        ' * Alter this variable, this is the starting point
        ' * for the deletion.
        ' * Example : path = "\\teacher\backup" 
        ' * Example : path = "N:\Logfiles" 
        
        Path = "C:\WINXPPro\TEMP" 
        
        ' * Alter this variable, if sub-folders should be processed
        ' * Process Sub folders Example : Subfolders = True 
        ' * Process Sub folders Example : Subfolders = False 
        
        Subfolders = False
        
        ' * Alter this variable to set the how many days old
        ' * the file should be before it is deleted.
        ' * Example : lifetime = date() - 20
        ' *           Will delete files that are 20 days old or more
        
        Lifetime = date() - 20 
        
        ' * Change the path to where the log file is.
        ' * Be sure the text file already exists or else 
        ' * script will fail.
        strLogFile = "c:\logs\fileDeleteLog.txt"
        
        ' *******************************************************
        ' Script starts at this point
        ' *******************************************************
        ' Declare a variable as an Array that will store a listing
        ' of files that will be checked.
        
        FilesArray = Array() 
        
        ' Create an instance of the FileSystemObject so that file
        ' information can be obtained.
        
        set fso = createobject("scripting.filesystemobject") 
        
        ' Call the SelectFiles procedure to Fill the array with 
        ' files and folders that will be deleted
        
        SelectFiles path, lifetime, FilesArray, Subfolders
        
        ' Process the FilesArray deleting files as we loop through
        
        numDeleted = 0 
        
        for n = 0 to ubound(FilesArray)
            ' Switch off error checking, so that errors are ignored
            on error resume next
            strFilePath = FilesArray(n).path
            ' Call the delete function to delete the selected file
            FilesArray(n).delete true 
            ' Handle any errors or results.  This could be modified
            ' to log to a text file.
            if err.number <> 0 then 
                Set objFile = FSO.OpenTextFile(strLogFile, 8) 
                objFile.WriteLine Now & vbTab & "ERROR - Unable to delete: " & strFilePath
                objFile.Close
            else 
                numDeleted = numDeleted + 1
                Set objFile = FSO.OpenTextFile(strLogFile, 8) 
                objFile.WriteLine Now & vbTab & "Deleted: " & strFilePath
                objFile.Close
         
            end if 
            ' Switch Error checking back to normal
            on error goto 0 
        next 
        
        Set objFile = FSO.OpenTextFile(strLogFile, 8) 
        objFile.WriteBlankLines(1)
        objFile.WriteLine "Total Files and Folders Deleted: " & numDeleted
        objFile.WriteBlankLines(4)
        objFile.Close
        
        sub SelectFiles(sPath,vlifetime,FilesArrayToKill,bIncludeSubFolders) 
            ' Switch off Error handling, errors ignored.
            on error resume next 
            'select files to delete and add to array... 
            set folder = fso.getfolder(sPath) 
            set files  = folder.files 
        
            ' Loop through files that have been found
            for each file in files 
                ' uses error trapping around access to the 
                ' Date property just to be safe 
                dtlastmodified = null
                on error resume Next 
                dtlastmodified = file.datelastmodified 
                on error goto 0 
        
                if not isnull(dtlastmodified) Then 
                    if dtlastmodified < vlifetime then 
                        count = ubound(FilesArrayToKill) + 1 
                        redim preserve FilesArrayToKill(count) 
                        Set FilesArrayToKill(count) = file 
                    end if 
                end if 
            next 
        
            ' If sub-folders are selected, call the procedure again to update
            ' the array with the contents.
        
            if bIncludeSubFolders then 
                for each fldr in folder.subfolders 
                    SelectFiles fldr.path,vlifetime,FilesArray,true 
                
                    ' uses error trapping around access to the 
                    ' Date property just to be safe 
                    dtlastmodified = null
                    on error resume Next 
                    dtlastmodified = fldr.datelastmodified 
                    on error goto 0 
        
                    if not isnull(dtlastmodified) Then 
                        if dtlastmodified < vlifetime then 
                            count = ubound(FilesArrayToKill) + 1 
                            redim preserve FilesArrayToKill(count) 
                            Set FilesArrayToKill(count) = fldr 
                        end if 
                    end if 
                next
            end if 
        end sub
        Regards,
        Jeremy

        Network Consultant/Engineer
        Baltimore - Washington area and beyond
        www.gma-cpa.com

        Comment


        • #5
          Re: Deleting Temp Files in User Profiles with VBS

          Can we include something like this into the script:

          Code:
          Option Explicit
          Dim objFSO, objFolder, objShell, objFile
          Dim strDirectory, strFile
          strDirectory = "c:\logs"
          strFile = "\fileDeleteLog.txt"
          
          ' Create the File System Object
          Set objFSO = CreateObject("Scripting.FileSystemObject")
          
          ' Check that the strDirectory folder exists
          If objFSO.FolderExists(strDirectory) Then
             Set objFolder = objFSO.GetFolder(strDirectory)
          Else
          Set objFolder = objFSO.CreateFolder(strDirectory)
          WScript.Echo "Just created " & strDirectory
          End If
          
          If objFSO.FileExists(strDirectory & strFile) Then
          Set objFolder = objFSO.GetFolder(strDirectory)
          Else
          Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
          Wscript.Echo "Just created " & strDirectory & strFile
          End If 
          
          set objFolder = nothing
          set objFile = nothing
          
          If err.number = vbEmpty then
          Set objShell = CreateObject("WScript.Shell")
          objShell.run ("Explorer" & " " & strDirectory & "\" )
          Else WScript.echo "VBScript Error: " & err.number
          End If
          
          WScript.Quit
          This is my signature.

          Comment


          • #6
            Re: Deleting Temp Files in User Profiles with VBS

            Sure thing.

            Code:
            ' ***************************************************
            ' * This script will delete all files in a folder and
            ' * sub-folder where when files are x number of days
            ' * old.
            ' *
            ' * Files will be deleted and not retained in the 
            ' * recycle bin.
            ' *
            ' * Alter the path and lifetime variables to your needs
            ' * Alter this variable, this is the starting point
            ' * for the deletion.
            ' * Example : path = "\\teacher\backup" 
            ' * Example : path = "N:\Logfiles" 
            
            Path = "C:\testDelete" 
            
            ' * Alter this variable, if sub-folders should be processed
            ' * Process Sub folders Example : Subfolders = True 
            ' * Process Sub folders Example : Subfolders = False 
            
            Subfolders = True
            
            ' * Alter this variable to set the how many days old
            ' * the file should be before it is deleted.
            ' * Example : lifetime = date() - 20
            ' *           Will delete files that are 20 days old or more
            
            Lifetime = date() - 20 
            
            ' * Change the path to where the log file is.
            ' * Be sure the text file already exists or else 
            ' * script will fail.
            strLogFile = "c:\logs\fileDeleteLog.txt"
            
            ' *******************************************************
            ' * Check if the log file exists
            ' *******************************************************
            strDirectory = "c:\logs"
            strFile = "\fileDeleteLog.txt"
            
            ' Create the File System Object
            Set objFSO = CreateObject("Scripting.FileSystemObject")
            
            ' Check that the strDirectory folder exists
            If objFSO.FolderExists(strDirectory) Then
               Set objFolder = objFSO.GetFolder(strDirectory)
            Else
            Set objFolder = objFSO.CreateFolder(strDirectory)
            WScript.Echo "Just created " & strDirectory
            End If
            
            If objFSO.FileExists(strDirectory & strFile) Then
            Set objFolder = objFSO.GetFolder(strDirectory)
            Else
            Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
            Wscript.Echo "Just created " & strDirectory & strFile
            End If 
            
            set objFolder = nothing
            set objFile = nothing
            
            If err.number = vbEmpty then
            Set objShell = CreateObject("WScript.Shell")
            objShell.run ("Explorer" & " " & strDirectory & "\" )
            Else WScript.echo "VBScript Error: " & err.number
            End If
            
            
            ' *******************************************************
            ' Script starts at this point
            ' *******************************************************
            ' Declare a variable as an Array that will store a listing
            ' of files that will be checked.
            
            FilesArray = Array() 
            
            ' Create an instance of the FileSystemObject so that file
            ' information can be obtained.
            
            set fso = createobject("scripting.filesystemobject") 
            
            ' Call the SelectFiles procedure to Fill the array with 
            ' files and folders that will be deleted
            
            SelectFiles path, lifetime, FilesArray, Subfolders
            
            ' Process the FilesArray deleting files as we loop through
            
            numDeleted = 0 
            
            
            for n = 0 to ubound(FilesArray)
                ' Switch off error checking, so that errors are ignored
                strFilePath = FilesArray(n).path '<-----------------------------Add
                'on error resume next
                ' Call the delete function to delete the selected file
                FilesArray(n).delete true 
                ' Handle any errors or results.  This could be modified
                ' to log to a text file.
                if err.number <> 0 then 
                    Set objFile = FSO.OpenTextFile(strLogFile, 8) 
                    objFile.WriteLine Now & vbTab & "ERROR - Unable to delete: " & strFilePath '<---------------------Change
                    objFile.Close
                else 
                    numDeleted = numDeleted + 1
                    Set objFile = FSO.OpenTextFile(strLogFile, 8) 
                    objFile.WriteLine Now & vbTab & "Deleted: " & strFilePath '<---------------------Change
                    objFile.Close
             
                end if 
                ' Switch Error checking back to normal
                on error goto 0 
            next 
            
            Set objFile = FSO.OpenTextFile(strLogFile, 8) 
            objFile.WriteBlankLines(1)
            objFile.WriteLine "Total Files and Folders Deleted: " & numDeleted
            objFile.WriteBlankLines(4)
            objFile.Close
            
            sub SelectFiles(sPath,vlifetime,FilesArrayToKill,bIncludeSubFolders) 
                ' Switch off Error handling, errors ignored.
               ' on error resume next 
                'select files to delete and add to array... 
                set folder = fso.getfolder(sPath) 
                set files  = folder.files 
            
                ' Loop through files that have been found
                for each file in files 
                    ' uses error trapping around access to the 
                    ' Date property just to be safe 
                    Wscript.echo "File path " &file.path
                    dtlastmodified = null
                    on error resume Next 
                    dtlastmodified = file.datelastmodified 
                    on error goto 0 
            
                    'if not isnull(dtlastmodified) Then 
                    '    if dtlastmodified < vlifetime then 
                            count = ubound(FilesArrayToKill) + 1 
                            redim preserve FilesArrayToKill(count) 
                            wscript.echo "Count = " &count
                            Set FilesArrayToKill(count) = file 
                    '    end if 
                    'end if 
                next 
            
                ' If sub-folders are selected, call the procedure again to update
                ' the array with the contents.
            
                if bIncludeSubFolders then 
                    for each fldr in folder.subfolders 
                        SelectFiles fldr.path,vlifetime,FilesArray,true 
                    
                        ' uses error trapping around access to the 
                        ' Date property just to be safe 
                        Wscript.echo "File path " &fldr.path
                        dtlastmodified = null
                        on error resume Next 
                        dtlastmodified = fldr.datelastmodified 
                        on error goto 0 
            
                        'if not isnull(dtlastmodified) Then 
                        '    if dtlastmodified < vlifetime then 
                                count = ubound(FilesArrayToKill) + 1 
                                redim preserve FilesArrayToKill(count) 
                                wscript.echo "Count = " &count
                                Set FilesArrayToKill(count) = fldr 
                        '    end if 
                        'end if 
                    next
                end if 
            end sub
            Regards,
            Jeremy

            Network Consultant/Engineer
            Baltimore - Washington area and beyond
            www.gma-cpa.com

            Comment


            • #7
              Re: Deleting Temp Files in User Profiles with VBS

              Ah ... I tried joining them together but I left some bits in I should have taken out... seems to be working however it is giving an error count for each file not deleted..

              correction... it doesn't appear to be deleting any - just listing them - is this a cause of the creating the txt file? also I'm thinking its a bit pointless to report back ....
              Last edited by Lan; 25th June 2007, 13:54. Reason: correction bit
              This is my signature.

              Comment


              • #8
                Re: Deleting Temp Files in User Profiles with VBS

                Ah yes, the echoing of the paths and count was for my testing, sorry about that. As for stuff not deleting, did you change the Lifetime variable?

                EDIT - What does the log file say? Is it showing that it deleted files or is it giving errors?

                EDIT - I had copied the code from my testing and some important lines were commented out. It should be correct now.

                Code:
                ' ***************************************************
                ' * This script will delete all files in a folder and
                ' * sub-folder where when files are x number of days
                ' * old.
                ' *
                ' * Files will be deleted and not retained in the 
                ' * recycle bin.
                ' *
                ' * Alter the path and lifetime variables to your needs
                ' * Alter this variable, this is the starting point
                ' * for the deletion.
                ' * Example : path = "\\teacher\backup" 
                ' * Example : path = "N:\Logfiles" 
                
                Path = "C:\testDelete" 
                
                ' * Alter this variable, if sub-folders should be processed
                ' * Process Sub folders Example : Subfolders = True 
                ' * Process Sub folders Example : Subfolders = False 
                
                Subfolders = True
                
                ' * Alter this variable to set the how many days old
                ' * the file should be before it is deleted.
                ' * Example : lifetime = date() - 20
                ' *           Will delete files that are 20 days old or more
                
                Lifetime = date() - 0 
                
                ' * Change the path to where the log file is.
                ' * Be sure the text file already exists or else 
                ' * script will fail.
                strLogFile = "c:\logs\fileDeleteLog.txt"
                
                ' *******************************************************
                ' * Check if the log file exists
                ' *******************************************************
                strDirectory = "c:\logs"
                strFile = "\fileDeleteLog.txt"
                
                ' Create the File System Object
                Set objFSO = CreateObject("Scripting.FileSystemObject")
                
                ' Check that the strDirectory folder exists
                If objFSO.FolderExists(strDirectory) Then
                   Set objFolder = objFSO.GetFolder(strDirectory)
                Else
                Set objFolder = objFSO.CreateFolder(strDirectory)
                WScript.Echo "Just created " & strDirectory
                End If
                
                If objFSO.FileExists(strDirectory & strFile) Then
                Set objFolder = objFSO.GetFolder(strDirectory)
                Else
                Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
                Wscript.Echo "Just created " & strDirectory & strFile
                End If 
                
                set objFolder = nothing
                set objFile = nothing
                
                If err.number = vbEmpty then
                Set objShell = CreateObject("WScript.Shell")
                objShell.run ("Explorer" & " " & strDirectory & "\" )
                Else WScript.echo "VBScript Error: " & err.number
                End If
                
                
                ' *******************************************************
                ' Script starts at this point
                ' *******************************************************
                ' Declare a variable as an Array that will store a listing
                ' of files that will be checked.
                
                FilesArray = Array() 
                
                ' Create an instance of the FileSystemObject so that file
                ' information can be obtained.
                
                set fso = createobject("scripting.filesystemobject") 
                
                ' Call the SelectFiles procedure to Fill the array with 
                ' files and folders that will be deleted
                
                SelectFiles path, lifetime, FilesArray, Subfolders
                
                ' Process the FilesArray deleting files as we loop through
                
                numDeleted = 0 
                
                
                for n = 0 to ubound(FilesArray)
                    ' Switch off error checking, so that errors are ignored
                    strFilePath = FilesArray(n).path 
                    on error resume next
                    ' Call the delete function to delete the selected file
                    FilesArray(n).delete true 
                    ' Handle any errors or results.  This could be modified
                    ' to log to a text file.
                    if err.number <> 0 then 
                        Set objFile = FSO.OpenTextFile(strLogFile, 8) 
                        objFile.WriteLine Now & vbTab & "ERROR: " & Err.Number & " " & Err.Dscription & " - Unable to delete: " & strFilePath 
                        objFile.Close
                    else 
                        numDeleted = numDeleted + 1
                        Set objFile = FSO.OpenTextFile(strLogFile, 8) 
                        objFile.WriteLine Now & vbTab & "Deleted: " & strFilePath 
                        objFile.Close
                 
                    end if 
                    ' Switch Error checking back to normal
                    on error goto 0 
                next 
                
                Set objFile = FSO.OpenTextFile(strLogFile, 8) 
                objFile.WriteBlankLines(1)
                objFile.WriteLine "Total Files and Folders Deleted: " & numDeleted
                objFile.WriteBlankLines(4)
                objFile.Close
                
                sub SelectFiles(sPath,vlifetime,FilesArrayToKill,bIncludeSubFolders) 
                    ' Switch off Error handling, errors ignored.
                    on error resume next 
                    'select files to delete and add to array... 
                    set folder = fso.getfolder(sPath) 
                    set files  = folder.files 
                
                    ' Loop through files that have been found
                    for each file in files 
                        ' uses error trapping around access to the 
                        ' Date property just to be safe 
                        dtlastmodified = null
                        on error resume Next 
                        dtlastmodified = file.datelastmodified 
                        on error goto 0 
                
                        if not isnull(dtlastmodified) Then 
                            if dtlastmodified < vlifetime then 
                                count = ubound(FilesArrayToKill) + 1 
                                redim preserve FilesArrayToKill(count) 
                                Set FilesArrayToKill(count) = file 
                            end if 
                        end if 
                    next 
                
                    ' If sub-folders are selected, call the procedure again to update
                    ' the array with the contents.
                
                    if bIncludeSubFolders then 
                        for each fldr in folder.subfolders 
                            SelectFiles fldr.path,vlifetime,FilesArray,true 
                        
                            ' uses error trapping around access to the 
                            ' Date property just to be safe 
                            dtlastmodified = null
                            on error resume Next 
                            dtlastmodified = fldr.datelastmodified 
                            on error goto 0 
                
                            if not isnull(dtlastmodified) Then 
                                if dtlastmodified < vlifetime then 
                                    count = ubound(FilesArrayToKill) + 1 
                                    redim preserve FilesArrayToKill(count) 
                                    Set FilesArrayToKill(count) = fldr 
                                end if 
                            end if 
                        next
                    end if 
                end sub
                Last edited by JeremyW; 25th June 2007, 14:27.
                Regards,
                Jeremy

                Network Consultant/Engineer
                Baltimore - Washington area and beyond
                www.gma-cpa.com

                Comment


                • #9
                  Re: Deleting Temp Files in User Profiles with VBS

                  heh after clicking ok about 200 times it gives permission denied and doesnt add anything into the log file...

                  so it creates the file, goes through the files counts them up and then fails on a file that is in use?
                  This is my signature.

                  Comment


                  • #10
                    Re: Deleting Temp Files in User Profiles with VBS

                    See my edit above. I had posted the script I used for testing and turned off the error handling as well as the date checking and also put in the echos. Everything should be corrected now.
                    Regards,
                    Jeremy

                    Network Consultant/Engineer
                    Baltimore - Washington area and beyond
                    www.gma-cpa.com

                    Comment


                    • #11
                      Re: Deleting Temp Files in User Profiles with VBS

                      Aaahehehehe easy mistake to make

                      I have a headache now
                      This is my signature.

                      Comment


                      • #12
                        Re: Deleting Temp Files in User Profiles with VBS

                        It turns out that I just has a use for this script! I can now attest that the date functionality does work (which I wasn't able to test earlier).

                        I hope you get good use out of the script.
                        Regards,
                        Jeremy

                        Network Consultant/Engineer
                        Baltimore - Washington area and beyond
                        www.gma-cpa.com

                        Comment


                        • #13
                          Re: Deleting Temp Files in User Profiles with VBS

                          Seems to work brilliantly! Top man

                          Added on a prompt fro a computer name and changed it slightly so it'll access it on the c$ of machines - so it'll work if you are an administrator - also it'll create a log file on the person running it but this could easily be changed to remote machine too... (also since I am here I've changed WINXPPRO to Windows - as thats the default for normal people ) - I would be tempted to put in another input box for ...

                          Code:
                          ' ***************************************************
                          ' * This script will delete all files in a folder and
                          ' * sub-folder where when files are x number of days
                          ' * old.
                          ' *
                          ' * Files will be deleted and not retained in the 
                          ' * recycle bin.
                          ' *
                          ' * Alter the path and lifetime variables to your needs
                          ' * Alter this variable, this is the starting point
                          ' * for the deletion.
                          ' * Example : path = "\\teacher\backup" 
                          ' * Example : path = "N:\Logfiles" 
                          ' Input for remote machine
                          RemPath = InputBox("Enter Computer Name to clean temporary files from WINDOWS\TEMP:", "Remote WINDOWS\TEMP Cleanup")
                          
                          Path = "\\" & RemPath & "\c$\WINDOWS\TEMP" 
                          
                          ' * Alter this variable, if sub-folders should be processed
                          ' * Process Sub folders Example : Subfolders = True 
                          ' * Process Sub folders Example : Subfolders = False 
                          
                          Subfolders = True
                          
                          ' * Alter this variable to set the how many days old
                          ' * the file should be before it is deleted.
                          ' * Example : lifetime = date() - 20
                          ' *           Will delete files that are 20 days old or more
                          
                          Lifetime = date() - 0 
                          
                          ' * Change the path to where the log file is.
                          ' * Be sure the text file already exists or else 
                          ' * script will fail.  Change this to RemPath & "\c$\logs" to store on remote machine
                          strLogFile = "c:\logs\" & RemPath & "fileDeleteLog.txt"
                          
                          ' *******************************************************
                          ' * Check if the log file exists
                          ' *******************************************************
                          strDirectory = "c:\logs"
                          strFile = "\" & RemPath & "fileDeleteLog.txt"
                          
                          ' Create the File System Object
                          Set objFSO = CreateObject("Scripting.FileSystemObject")
                          
                          ' Check that the strDirectory folder exists
                          If objFSO.FolderExists(strDirectory) Then
                             Set objFolder = objFSO.GetFolder(strDirectory)
                          Else
                          Set objFolder = objFSO.CreateFolder(strDirectory)
                          WScript.Echo "Just created " & strDirectory
                          End If
                          
                          If objFSO.FileExists(strDirectory & strFile) Then
                          Set objFolder = objFSO.GetFolder(strDirectory)
                          Else
                          Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
                          Wscript.Echo "Just created " & strDirectory & strFile
                          End If 
                          
                          set objFolder = nothing
                          set objFile = nothing
                          
                          If err.number = vbEmpty then
                          Set objShell = CreateObject("WScript.Shell")
                          objShell.run ("Explorer" & " " & strDirectory & "\" )
                          Else WScript.echo "VBScript Error: " & err.number
                          End If
                          
                          
                          ' *******************************************************
                          ' Script starts at this point
                          ' *******************************************************
                          ' Declare a variable as an Array that will store a listing
                          ' of files that will be checked.
                          
                          FilesArray = Array() 
                          
                          ' Create an instance of the FileSystemObject so that file
                          ' information can be obtained.
                          
                          set fso = createobject("scripting.filesystemobject") 
                          
                          ' Call the SelectFiles procedure to Fill the array with 
                          ' files and folders that will be deleted
                          
                          SelectFiles path, lifetime, FilesArray, Subfolders
                          
                          ' Process the FilesArray deleting files as we loop through
                          
                          numDeleted = 0 
                          
                          
                          for n = 0 to ubound(FilesArray)
                              ' Switch off error checking, so that errors are ignored
                              strFilePath = FilesArray(n).path 
                              on error resume next
                              ' Call the delete function to delete the selected file
                              FilesArray(n).delete true 
                              ' Handle any errors or results.  This could be modified
                              '100 to log to a text file.
                              if err.number <> 0 then 
                                  Set objFile = FSO.OpenTextFile(strLogFile, 8) 
                                  objFile.WriteLine Now & vbTab & "ERROR: " & Err.Number & " " & Err.Dscription & " - Unable to delete: " & strFilePath 
                                  objFile.Close
                              else 
                                  numDeleted = numDeleted + 1
                                  Set objFile = FSO.OpenTextFile(strLogFile, 8) 
                                  objFile.WriteLine Now & vbTab & "Deleted: " & strFilePath 
                                  objFile.Close
                           
                              end if 
                              ' Switch Error checking back to normal
                              on error goto 0 
                          next 
                          
                          Set objFile = FSO.OpenTextFile(strLogFile, 8) 
                          objFile.WriteBlankLines(1)
                          objFile.WriteLine "Total Files and Folders Deleted: " & numDeleted
                          objFile.WriteBlankLines(4)
                          objFile.Close
                          
                          sub SelectFiles(sPath,vlifetime,FilesArrayToKill,bIncludeSubFolders) 
                              ' Switch off Error handling, errors ignored.
                              on error resume next 
                              'select files to delete and add to array... 
                              set folder = fso.getfolder(sPath) 
                              set files  = folder.files 
                          
                              ' Loop through files that have been found
                              for each file in files 
                                  ' uses error trapping around access to the 
                                  ' Date property just to be safe 
                                  dtlastmodified = null
                                  on error resume Next 
                                  dtlastmodified = file.datelastmodified 
                                  on error goto 0 
                          
                                  if not isnull(dtlastmodified) Then 
                                      if dtlastmodified < vlifetime then 
                                          count = ubound(FilesArrayToKill) + 1 
                                          redim preserve FilesArrayToKill(count) 
                                          Set FilesArrayToKill(count) = file 
                                      end if 
                                  end if 
                              next 
                          
                              ' If sub-folders are selected, call the procedure again to update
                              ' the array with the contents.
                          
                              if bIncludeSubFolders then 
                                  for each fldr in folder.subfolders 
                                      SelectFiles fldr.path,vlifetime,FilesArray,true 
                                  
                                      ' uses error trapping around access to the 
                                      ' Date property just to be safe 
                                      dtlastmodified = null
                                      on error resume Next 
                                      dtlastmodified = fldr.datelastmodified 
                                      on error goto 0 
                          
                                      if not isnull(dtlastmodified) Then 
                                          if dtlastmodified < vlifetime then 
                                              count = ubound(FilesArrayToKill) + 1 
                                              redim preserve FilesArrayToKill(count) 
                                              Set FilesArrayToKill(count) = fldr 
                                          end if 
                                      end if 
                                  next
                              end if 
                          end sub
                          This is my signature.

                          Comment


                          • #14
                            Re: Deleting Temp Files in User Profiles with VBS

                            Looks good.

                            Just a minor syntax note:

                            Code:
                            strLogFile = "c:\logs\" & RemPath & "fileDeleteLog.txt"
                            should be
                            Code:
                            strLogFile = "\\" & RemPath & "\c$\logs\fileDeleteLog.txt"



                            And
                            Code:
                            strFile = "\" & RemPath & "fileDeleteLog.txt"
                            should be left
                            Code:
                            strFile = "\fileDeleteLog.txt"



                            but
                            Code:
                            strDirectory = "c:\logs"
                            should be
                            Code:
                            strDirectory = "\\" RemPath & "\c$\logs"
                            And to eliminate typing in all those "\\" you could add this bit of code just after the Inputbox so that the backslashes are included in the variable
                            Code:
                            If NOT Left(RemPath,2) = "\\" Then
                                RemPath = "\\" & RemPath
                            End If
                            Regards,
                            Jeremy

                            Network Consultant/Engineer
                            Baltimore - Washington area and beyond
                            www.gma-cpa.com

                            Comment


                            • #15
                              Re: Deleting Temp Files in User Profiles with VBS

                              Originally posted by JeremyW View Post
                              Looks good.

                              Just a minor syntax note:

                              Code:
                              strLogFile = "c:\logs\" & RemPath & "fileDeleteLog.txt"
                              should be
                              Code:
                              strLogFile = "\\" & RemPath & "\c$\logs\fileDeleteLog.txt"
                              And
                              Code:
                              strFile = "\" & RemPath & "fileDeleteLog.txt"
                              should be left
                              Code:
                              strFile = "\fileDeleteLog.txt"
                              but
                              Code:
                              strDirectory = "c:\logs"
                              should be
                              Code:
                              strDirectory = "\\" RemPath & "\c$\logs"
                              these bits will create the log file on the remote machine won't it? I had it just create it on my machine and add the target machine name into the name of the log file so I knew which ones I'd cleaned up rather than leaving the log files on the remote machines... still wondering which would be more useful - me knowing what I've done or just leaving the log file on the remote machine to what has been done on it...

                              e.g. I run the script and target it at fred
                              log file fredfileDeletelog.txt gets created on my machine
                              fred's files get deleted.
                              I run it again on Barry
                              I get the log file BarryfileDeletelog.txt along with fredfileDeletelog.txt

                              I can then see that i've run it on Barry and Fred - whereas the log files aren't hitting Barry or Fred's machines as they really don't care ;p


                              - this however does look useful... going to have a quick go at this

                              And to eliminate typing in all those "\\" you could add this bit of code just after the Inputbox so that the backslashes are included in the variable
                              Code:
                              If NOT Left(RemPath,2) = "\\" Then
                                  RemPath = "\\" & RemPath
                              End If
                              This is my signature.

                              Comment

                              Working...
                              X