Announcement

Collapse
No announcement yet.

Exclude Specified File/Folder Names (VBS)

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

  • Exclude Specified File/Folder Names (VBS)

    Following on from this where we ended up the following which will search in a specified folder directory on a remote machine and delete files based on age...

    (set to 10 days at the moment) - tested and works fine. But simply I wondered if it were possible to exclude specific folders from a list...

    For Example;
    delete all the files/folders over 10 days old in 'Folder1' and 'Folder2' but not from 'Folder1\Important Docs' - 'cause that'd be silly....

    I'm guessing I might have to define a list of words for it to 'skip' as it searches...


    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.
    ' Input for remote machine
    
    
    RemPath = InputBox("Enter Computer Name or drive to clean:", "Remote\Local Cleanup")
    
    If Len(RemPath) = 1 OR (Len(RemPath) = 2 AND Right(RemPath, 1) = ":") Then
        If Len(RemPath) = 1 Then
            strRoot = RemPath & ":\"
        Else
            strRoot = RemPath & "\"
        End If
        RemPath = "\\local"
        
    ElseIf NOT Left(RemPath,2) = "\\" Then
        RemPath = "\\" & RemPath
        strRoot = RemPath & "\c$\"
    Else
        Wscript.Echo "Something's wrong... try running the script again"
        Wscript.Quit
    End If
    
    
    '---------------------Add array here----------------------------
    Dim arrDirPaths()
    intSize = 0
    intLoop = 0
    
    Do Until intLoop = 1
        strDirPath = InputBox("Please enter the directory you want to clean." & VbCrLF _
            & "e.g. 'windows\temp'" & VbCrLF & VbCrLF & "If you have all the diretories entered then " _
            & "leave the box blank and click OK.", "Directory Path")
        If NOT strDirPath = "" Then
            ReDim Preserve arrDirPaths(intSize)
            arrDirPaths(intSize) = strDirPath
            intSize = intSize + 1
        Else
            intDialogBox = Msgbox("Are you ready to proceed?" & vbCrLF & vbCrLF & _
                                  "Yes to continue" & vbCrLF & "No to enter more paths" _
                                  & vbCrLF & "Cancel to exit the script" ,3,"Path Input...?")
            If intDialogBox = 2 Then
                Wscript.Quit
            ElseIf intDialogBox = 6 Then
                intLoop = 1
            End If
        End If
    Loop
    '--------------add check before proceeding----------------
    If intSize = 0 Then
        Wscript.Echo "No directory was entered. The script will now quit"
        Wscript.quit
    End If
    
    
    
    ' * 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() - 10 
    
    ' * 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\" & Right(RemPath, Len(RemPath) - 2) & "_fileDeleteLog.txt"
    
    
    
    ' *******************************************************
    ' * Check if the log file exists
    ' *******************************************************
    strDirectory = "c:\logs"
    strFile = "\" & Right(RemPath, Len(RemPath) - 2) & "_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
    
    numDeleted = 0
    
    
    '---------------------Add "For Each" loop here----------------------------
     
    
    
    For i = 0 to intSize -1
        Path = strRoot & arrDirPaths(i)
    
       
        ' 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
    
        
            
        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 
    
    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 fso = createobject("scripting.filesystemobject") 
        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.

  • #2
    Re: Exclude Specified File/Folder Names (VBS)

    I'm sure it can be done in just two lines in a batch file, I don't mean to throw all your beautiful code away but there is a very easy alternative way.

    Using robocopy (from Server 2003 resource kit tools) with switches that exclude certain files or folders, and with certain age constraints, they can be MOVED to a destination such as another disk.

    The second line of the batch file deletes everything on the destination, using RD with /s. Hey presto, job done.

    Here's some relevant robocopy switches:
    /MOVE :: MOVE files AND dirs (delete from source after copying).
    /MAXAGE:n :: MAXimum file AGE - exclude files older than n days/date.
    /MINAGE:n :: MINimum file AGE - exclude files newer than n days/date.
    /MAXLAD:n :: MAXimum Last Access Date - exclude files unused since n.
    /MINLAD:n :: MINimum Last Access Date - exclude files used since n.
    (If n < 1900 then n = n days, else n = YYYYMMDD date).
    /XF file [file]... :: eXclude Files matching given names/paths/wildcards.
    /XD dirs [dirs]... :: eXclude Directories matching given names/paths.
    Last edited by PaulH; 1st July 2007, 20:53.
    Best wishes,
    PaulH.
    MCP:Server 2003; MCITP:Server 2008; MCTS: SBS2008

    Comment


    • #3
      Re: Exclude Specified File/Folder Names (VBS)

      Robocopy, say you?
      Then UtilitySpotlight is a must. Robocopy's GUI !

      Sorin Solomon


      In order to succeed, your desire for success should be greater than your fear of failure.
      -

      Comment


      • #4
        Re: Exclude Specified File/Folder Names (VBS)

        Hi Sorin

        Yes, Sorin has suggested a very useful GUI to help with getting all those pesky switches just right. The only glitch with it, just so you're aware, is that the switches in the GUI don't exactly match up with the Robocopy command line ones. 99% of them do, but I have tripped over the GUI once or twice - this depends on the exact version of Robocopy, I do believe, so they may have straightened things out by now.
        Best wishes,
        PaulH.
        MCP:Server 2003; MCITP:Server 2008; MCTS: SBS2008

        Comment


        • #5
          Re: Exclude Specified File/Folder Names (VBS)

          Hey, Paul .
          I am using the Robocopy version that comes with the 2003Server RKT. It is version XP010 and they say it should be fully compatible with the GUI.
          As a matter of fact, I wasn't aware there are few versions of Robocopy around

          Sorin Solomon


          In order to succeed, your desire for success should be greater than your fear of failure.
          -

          Comment


          • #6
            Re: Exclude Specified File/Folder Names (VBS)

            The GUI is a good tool for most of the switches, but not all. I've had a look at UtilitySpotlight (latest version, 3.1.1) and I can't see any GUI controls to put the age-related switches in there, that are most useful to the OP, so you'll have to use the command line. There are many more switches you can use than the ones in my first post, but the ones there will achieve your objective.

            Best wishes,
            Best wishes,
            PaulH.
            MCP:Server 2003; MCITP:Server 2008; MCTS: SBS2008

            Comment


            • #7
              Re: Exclude Specified File/Folder Names (VBS)

              hmm yea, I just didn't want to end up installing tool/packs on multiple machines... 'cause the idea is there will be a few people using this if I can get it working well. The more foolproof the better sometimes though.. so I wanted to make sure I - or anyone else - didn't delete anything important
              This is my signature.

              Comment


              • #8
                Re: Exclude Specified File/Folder Names (VBS)

                oh, robocopy is only one small part of the pack - just take robocopy.exe out and it'll work on it's own, it's a nice tiny tool.
                Best wishes,
                PaulH.
                MCP:Server 2003; MCITP:Server 2008; MCTS: SBS2008

                Comment


                • #9
                  Re: Exclude Specified File/Folder Names (VBS)

                  Yep, it'd still require me to go and put it on any machine I wanted to run it from
                  This is my signature.

                  Comment


                  • #10
                    Re: Exclude Specified File/Folder Names (VBS)

                    I don't understand - either you walk around installing the VBscript (or a shortcut to it) or the VBScript is running on the server from a logoff script (or whatever, requiring no walking) - I'm not sure which in your case, but either way, using robocopy requires no more shoe mileage. You don't have to install robocopy. It just runs, even from a share, if you like, as part of batch file or script that calls it - use it any way you like. It's a standalone executable.

                    I hope it helps you because in one line you can achieve so much particularly in connection with file ages etc which is exactly what you want to do.
                    Best wishes,
                    PaulH.
                    MCP:Server 2003; MCITP:Server 2008; MCTS: SBS2008

                    Comment


                    • #11
                      Re: Exclude Specified File/Folder Names (VBS)

                      the idea was a link to the .vbs file that sits on a server and the peeps that use it can just double click to run it, whack in a computer name/folders and sit back and relax...

                      I'll have a look into running a batch file and having robocopy in the same location...

                      it does defeat the object of that vbs thou lol
                      This is my signature.

                      Comment


                      • #12
                        Re: Exclude Specified File/Folder Names (VBS)

                        Was there ever a script created that could do this is vbscript? If so could you please show me? as this is what I'm trying to do. Unfortunately I cannot use robocopy and it has to be done in vbscript.

                        Comment


                        • #13
                          Re: Exclude Specified File/Folder Names (VBS)

                          http://forums.petri.com/showthread.php?t=17636

                          see that thread - I got it working locally but not remotely...

                          ill go sort an example out in a mo...

                          this one I ended up having that moved folders apart from those with a specific name into another named folder locally... it can probably be modified for deleting instead...

                          it might need some tweaking as i was playing around with this a lot to try and get it working using a UNC connection

                          Code:
                          strArchDate = "archive_" & FormatDateTime(date(),vblongdate)
                          
                            Dim objFSO        : Set objFSO        = CreateObject("Scripting.FileSystemObject" )
                            Dim objFolder     : Set objFolder     = objFSO.GetFolder( "C:\_test_" )
                            Dim colSubFolders : Set colSubFolders = objFolder.Subfolders
                            Dim dicSelFolders : Set dicSelFolders = CreateObject("Scripting.Dictionary" )
                          
                          dim Movesys
                          set Movesys = CreateObject("Scripting.FileSystemObject")
                          'If Movesys.FolderExists(c:\_test_\Folder (1)") Then
                          '   Movesys.MoveFolder "c:\_test_\Folder (1)", "c:\_test_\_Archive_" & 'FormatDateTime(date(),vblongdate) & "\"
                          'End If
                          
                          
                            dicSelFolders.Add "admin", ""
                            dicSelFolders.Add "local"  , ""
                            dicSelFolders.Add strArchDate  , ""
                          
                            Dim objSubfolder
                            For Each objSubfolder in colSubfolders
                          '     On Error Resume Next
                                If dicSelFolders.Exists( LCase( objSubfolder.Name ) ) Then
                                   WScript.Echo "ignoring", objSubfolder.Path
                                Else
                                   WScript.Echo "handling", objSubfolder.Path
                                   Movesys.MoveFolder objSubfolder.Path, "c:\_test_\_Archive_" & FormatDateTime(date(),vblongdate) & "\"
                                End If
                            Next
                          Last edited by Lan; 6th September 2007, 11:22. Reason: adding example
                          This is my signature.

                          Comment

                          Working...
                          X