Announcement

Collapse
No announcement yet.

Help with script pulled from forum

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

  • Help with script pulled from forum

    Hi All,

    I pulled a script from this forum that was written by JeremyW.


    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:\Intel12.3" 
    
    ' * 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
    
    
    ' * Directory and filename for the logfile
    strDirectory = "c:\logs"
    strFile = "fileDeleteLog.txt"
    
    strLogFile = strDirectory & "\" & strFile
    
    ' *******************************************************
    ' * Check if the log file exists
    ' *******************************************************
    
    
    ' 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)
    End If
    
    If objFSO.FileExists(strDirectory & strFile) Then
    Set objFolder = objFSO.GetFolder(strDirectory)
    Else
    Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
    End If 
    
    set objFolder = nothing
    set objFile = nothing
    
    If err.number <> 0 then
    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

    It goes through a specified folder structure and deletes files and folders over a certain date. Can someone tell me how I might alter this script to delete the files only and not the subfolders? Also, I dont really need the date function, I am just running this script once a week to delete everything. If I enter 0 in the lifetime variable will this accomplish what I am after?

    TIA,

    R

  • #2
    Re: Help with script pulled from forum

    Can someone tell me how I might alter this script to delete the files only and not the subfolders? Also, I dont really need the date function
    The easiest way is by using a command-line (or batch):
    @Erase "path" /S /F /A /Q

    You can run this same command-line also by vbs;
    Code:
    strPath = "%temp%"
    logfile = "c:\%computername%-EraseFolder.log"
    
    strCommand = "Erase """& strPath &""" /S /F /A /Q"
    
    Set oFS = CreateObject("Scripting.FileSystemObject")
    Set objShell = WScript.CreateObject("WScript.Shell")
    If oFS.FolderExists _
     (objShell.ExpandEnvironmentStrings(strPath)) Then
     objShell.run _
     "%comspec% /c (" & strCommand & ") >"""& logfile &""" 2>&1", _
     0, False
    End If
    \Rems

    This posting is provided "AS IS" with no warranties, and confers no rights.

    __________________

    ** Remember to give credit where credit's due **
    and leave Reputation Points for meaningful posts

    Comment


    • #3
      Re: Help with script pulled from forum

      Thank you very much for your reply. To make things a little more difficult..I realize now I may need something else. Say I have folder structure such as

      c:\delete\username\<files and folders here>

      So basically I have a folder called delete with lots of subfolders inside of it that are usernames. Inside of the usernames folder I have files and folders that are associaed with each user. When I run my script, I want the username subfolders to stay but everything underneath to be deleted, including files and folders. so my first post was actually incorrect.

      be careful what you ask for i suppose!

      thanks again

      Comment


      • #4
        Re: Help with script pulled from forum

        No problem.

        Still, is using a batch the easiest way to accomplish your request;


        IMPORTANT NOTE: I have EDIT the code, Jan 30 2008 14:32! The new version is 'Batch version 2'

        sample *.cmd file:
        Code:
        :: This batch enumerate the folders in the 'target' path"
        :: then only within each folder, it deletes files and subfolders.
        ::
        :: Batch version 2
        ::
        
        @echo off
        
        (Set Target=%temp%) 
        (Set Logfile=c:\%computername%-EraseFolder.log)
        
        :: Delete all files
        (Set Target=%Target:"=%)
        title,DelTree %Target%&COLOR 9E
        
        If EXIST "%Target%",(
           PushD "%Target%" &&(
         :: Loop through every base folder in the path...
            For /f "Tokens=*" %%* in ('dir /AD /B 2^>NUL') Do (
             PushD "%%*" &(
             ATTRIB -S -H -R -A /D /S
             Erase "*.*" /S /F /A /Q >>"%Logfile%" 2>&1
           :: And Delete all subfolders from each base folder...
              For /f "Tokens=*" %%! in ('dir /AD /B 2^>NUL') Do (
              RMDIR "%%!" /Q /S) )& PopD
         ) )& PopD )
        (Test this batch first!)


        \Rems




        - EDIT <- EDIT-again

        it is also possible to move the 2 lines:
        ATTRIB -S -H -R -A /D /S
        Erase "*.*" /S /F /A /Q >"%Logfile%" 2>&1

        both a little bit more up, just after the line: PushD "%Target%" &(
        This adjustment concerns the deletion of files only! (not subfolders, the subfolders are removed by the RMDIR command)
        explanation:
        In the example, all files that only exists in the subfolders of the 'target folder' are being deleted.
        Now - when moving the two lines up to the new position - then, also files exists in the 'target' folder it self are going to be deleted.
        (ps if you would skip those 2 lines completely, then also the files in the first subfolders stay and only the subfolders within in the subfolder of the target folder will be deleted completely)
        Last edited by Rems; 30th January 2008, 14:51. Reason: added important brackets in the batch code!!!

        This posting is provided "AS IS" with no warranties, and confers no rights.

        __________________

        ** Remember to give credit where credit's due **
        and leave Reputation Points for meaningful posts

        Comment


        • #5
          Re: Help with script pulled from forum

          Thank you very much! I appreciate your time. This worked well for me. Just for my own knowledge, the logfile only consists of the last subfolder deleted items, what makes this happen?

          again, thank you!!

          Comment


          • #6
            Re: Help with script pulled from forum

            Because in the first version of the batch the files were deleted from the 'target folder' and ALL subfolders in one run. So it was possible to re-write the logfile.
            In the latest version, the batch loop through every base folder in the target folder, then delete all files from that folder, every time the lofgfile is rewritten with just thje latest information.

            Instead of re-writing, the information now should be appended to the logfile. Therefor change the > sign into >> sign for directing the output to the logfile.
            Note, Because of this change, the logfile will grow every time you run this batch, because the previous information won't be deleted any more. Optionally you can add a date/time stamp to the logfile name, so that it will create separate logfiles every run.


            example how to get a date/time stamp:
            Code:
            :: http://www.robvanderwoude.com/datetiment.html
            
            :: EXAMPLE
            :: only works for windows xp and newer
            
            @ECHO OFF
            
            :: Use WMIC to retrieve date and time
            WMIC.EXE Alias /? >NUL 2>&1 || GOTO:EOF
            FOR /F "skip=2 tokens=2-7 delims=," %%A IN (
             'WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:csv') DO (
             SET/A"SortDate=10000*%%F+100*%%D+%%A" & SET/A"SortTime=10000*%%B+100*%%C+%%E" )
            
            Set "DateTime=%SortDate%-%SortTime%"
            
            (Set Logfile=c:\%computername%-EraseFolder_%DateTime%_.log)
            
            
            :: Test the results:
            echo %Logfile%
            echo.&pause

            This posting is provided "AS IS" with no warranties, and confers no rights.

            __________________

            ** Remember to give credit where credit's due **
            and leave Reputation Points for meaningful posts

            Comment


            • #7
              Re: Help with script pulled from forum

              Ahhh...gotcha. thanks for your help!

              Comment

              Working...
              X