Announcement

Collapse
No announcement yet.

a script to delete recursively folder with numeric value only with older than certain

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

  • a script to delete recursively folder with numeric value only with older than certain

    Hi All,

    I'm just a beginner ins scripting, I'd like to modify the following script so that it can have further validation of deleting only a certain folder and it's content with numeric name

    input parameter
    C:\data --> the starting directory
    30 --> days older than today

    C:\data\1234 --> delete
    C:\data\5678 --> delete
    C:\data\abc123 --> don't delete
    c:\data\123abc --> don't delete

    so the script can just delete whatever inside the first two directory not the last two directory. (if the dir. name is all numeric then deltree or RD).

    I wonder if it can be any simpler ?

    Thanks.



    Code:
    ' Objective: To delete old files from a given folder and all subfolders below
    ' Created by: MAK
    ' Created Date: June 21, 2005
    ' Usage: cscript deloldfiles.vbs c:\dba\log 3
    '      : It deletes files older than 3 days
    Set objArgs = WScript.Arguments
    FolderName =objArgs(0)
    Days=objArgs(1)
     
    set fso = createobject("scripting.filesystemobject")
    set folders = fso.getfolder(FolderName)
    datetoday = now()
    newdate = dateadd("d", Days*-1, datetoday)
    wscript.echo "Today:" & now()
    wscript.echo "Started deleting files older than :" & newdate 
    wscript.echo "________________________________________________"
    wscript.echo ""
    recurse folders 
    wscript.echo ""
    wscript.echo "Completed deleting files older than :" & newdate 
    wscript.echo "________________________________________________"
     
    sub recurse( byref folders)
      set subfolders = folders.subfolders
      set files = folders.files
      wscript.echo ""
      wscript.echo "Deleting Files under the Folder:" & folders.path
      wscript.echo "__________________________________________________________________________"
      for each file in files
        if file.datelastmodified < newdate then
          wscript.echo "Deleting " & folders.path & "\" & file.name & " last modified: " & file.datelastmodified
          on error resume next
        file.delete
        end if
        
      next  
     
      for each folder in subfolders
        recurse folder
      next  
     
      set subfolders = nothing
      set files = nothing
     
    end sub

  • #2
    Re: a script to delete recursively folder with numeric value only with older than cer

    Originally posted by Albertwt View Post
    if the dir. name is all numeric then deltree or RD

    I wonder if it can be any simpler ?
    You can use RegExp, to define a pattern like,
    oRegExp.Pattern = "^\d+$"
    or,
    oRegExp.Pattern = "^[0-9]+$"
    then test this pattern oRegExp.Test("foldername") on the names of each subfolder recursively.

    The scripting.filesystemobject does not have a RMDIR method, you'll have to use recursion also for the found folders that matched your criteria to enumerate and then delete each file and subfolder that exist under it prior to the deletion of the folder itself.


    So you like to delete also all subfolder(s), no matter what their name look like, if exist under a folder with a digits-only name?

    => similar to this command in MS-DOS:
    RMDIR /S /Q "C:\data\1234"
    RMDIR /S /Q "C:\data\A-Zfolder\3456"
    This will delete all files, subfolders under the matching folder and the folder itself without a warning.


    The sample script you showed us is comparing the 'date last modified' attribute of the Files (just files here), do you still like to use this "days-old" condition also in the new script? - how? and against what?


    You also mensioned DELTREE as an example, on what Operating Systems exactly are you using this script?


    \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: a script to delete recursively folder with numeric value only with older than cer

      Hi Rems,

      thanks for the reply, this script will be used in the Windows Server 2003 environment.

      so i shall use the following initialization:

      Code:
      Set oRegExp = New RegExp
      And yes, i think it would be better if the script can just compare the folder date created too, i don't know if the file also needs to be deleted manually first then the dir. ?
      Last edited by Albertwt; 2nd September 2009, 08:40.

      Comment


      • #4
        Re: a script to delete recursively folder with numeric value only with older than cer

        Originally posted by Rems View Post
        You can use RegExp, to define a pattern like,
        oRegExp.Pattern = "^\d+$"
        or,
        oRegExp.Pattern = "^[0-9]+$"
        then test this pattern oRegExp.Test("foldername") on the names of each subfolder recursively.

        The scripting.filesystemobject does not have a RMDIR method, you'll have to use recursion also for the found folders that matched your criteria to enumerate and then delete each file and subfolder that exist under it prior to the deletion of the folder itself.


        So you like to delete also all subfolder(s), no matter what their name look like, if exist under a folder with a digits-only name?

        => similar to this command in MS-DOS:
        RMDIR /S /Q "C:\data\1234"
        RMDIR /S /Q "C:\data\A-Zfolder\3456"
        This will delete all files, subfolders under the matching folder and the folder itself without a warning.


        The sample script you showed us is comparing the 'date last modified' attribute of the Files (just files here), do you still like to use this "days-old" condition also in the new script? - how? and against what?


        You also mensioned DELTREE as an example, on what Operating Systems exactly are you using this script?


        \Rems
        Hi Rems,

        Unfortunately the script doesn't delete the directory with numerical name, only the files that gets deleted.

        '################################################# ############################'
        Set objArgs = WScript.Arguments
        strFolder =objArgs(0)
        intDays=objArgs(1)

        Set objFSO = CreateObject("Scripting.FileSystemObject")
        Set objFolders = objFSO.GetFolder(strFolder)

        Set oRegExp = New RegExp
        oRegExp.Pattern = "^[0-9]+$"

        objToday = Now()
        objPastDate = DateAdd("d", intDays*-1, objToday)

        wscript.echo "Today: " & now()
        wscript.echo "***********************************"
        wscript.echo "Started deleting files older than :" & objPastDate
        wscript.echo "***********************************"
        wscript.echo ""

        Recurse objFolders

        wscript.echo ""
        wscript.echo "*************************************"
        wscript.echo "Completed deleting files older than :" & objPastDate
        wscript.echo "*************************************"

        '================================================= ============================='
        Sub Recurse(ByRef objFolders)
        Set objSubFolders = objFolders.SubFolders
        Set objFiles = objFolders.Files

        REM For Each File In objFiles
        REM If File.DateLastModified < objPastDate Then
        REM On Error Resume Next
        REM File.Delete
        REM End If
        REM Next

        For Each Folder In objSubFolders
        If Folder.DateLastModified < objPastDate and oRegExp.Test(CStr(Folder)) Then
        On Error Resume Next
        wscript.echo "Deleting folder: " & Folder
        objFSO.DeleteFolder Folder.Path, True
        Else
        Recurse Folder
        End If
        Next

        Set objSubFolders = Nothing
        Set objFiles = Nothing

        End Sub
        '================================================= ============================='

        '################################################# ############################'
        Last edited by Albertwt; 4th September 2009, 07:28.

        Comment


        • #5
          Re: a script to delete recursively folder with numeric value only with older than cer

          Originally posted by Albertwt View Post
          Hi Rems,
          Unfortunately the script doesn't delete the directory with numerical name, only the files that gets deleted.
          Hi Albertwt,

          In your script the folowing comparison is not entirely correct,
          Code:
          If Folder.DateLastModified < objPastDate and oRegExp.Test(CStr(Folder)) Then
          because CStr(Folder) happen to result the Folder.path property here, while you should just test the pattern of the Folder.name property instead.

          Also, in your script you call a routine that recursively enummerate the subfolders. During this process you delete found folders that are matching a certain criteria =but= after the deletion of a folder you still using that folder's object as an argument to call the Recurse routine again. To solve this you should use: IF it_is_a_match THEN Folder.delete() ELSE For Each objFolder In Folder.SubFolders -> Recurse objFolder END IF.

          To avoid that everything in OR the startingDirectory itself being deleted you now have to start the enumeration of the base subfolders of the startingDirectory before calling the sub routine (as showed in the sample below).

          _
          Note that the DateLastModified property of a folder will update only if a file or subfolder is added_to OR removed_from that folder OR, when a file name or subfolder name that exist directly in that folder has been changed. The propery is Not updated when a file content has been changed or, when modifications were done in one of the subfolders.

          Unlike I stated in my previous reply (was confusing using WMI to delete a folder in Windows XP at SP level 2) the fso.deletefolder("path") method as wel as the objectFolder.delete() method both in fact are deleting the folder three. However by doing so you would not be able anymore to check the last_modified date of the folders or files under it.

          _
          If you need to delete folders in a tree one by one (like in the sample below), then start deleting from the lowest folder in the tree and work the way up.
          The sample below does not directly delete the folder. A separate routine is called to delete the "old" files from the folder/subfolders first, then delete each folder in the tree only if that folder is empty.

          Not sure if this script below do what you want though,
          If the script below finished - and still a folder (/tree starting) with a digits-only name exist, that means that there are one or more files still exist in the folder or in one of the subfolders - the file and its folder were not deleted because the content of the file was recently changed.
          Code:
          '# vbscript -
          '# Enumerate subfolders recusively beginning at "startingDirectory"
          '# 
          '# If a subfolder found with a 'digits-only name' a new routine is
          '# called for this folder.
          '# This routine recusively go down the trees. On its way
          '# it delete the files older than 30 days.
          '# Then it start deleting only the folders in the tree that are empty.
          '# (http://forums.petri.com/showthread.php?t=39661)
          
          ' Option explicit
          
          Const Force = TRUE
          
          Dim oRegExp, fso, DaysOld, FolderName, baseFolders
          
          Dim startingDirectory, filesOlderThen
          FolderName = "C:\test\TEST"
          filesOlderThen = 30 '(in days)
          
          DaysOld = dateadd("d", -filesOlderThen, now)
          
          set oRegExp = New RegExp: oRegExp.Pattern = "^\d+$"
          set fso = createobject("scripting.filesystemobject")
          set startingDirectory = fso.getfolder(FolderName)
          
          For each baseFolders in startingDirectory.subfolders
             Recurse baseFolders
          Next
          
          wscript.echo "Completed"
           
          sub Recurse(Folder)
             Dim objFolder
             ' on error resume next
          
             If oRegExp.Test(Folder.name) Then
               DelTree Folder
             Else
          
               For each objFolder in Folder.subfolders
                 Recurse objFolder
               Next
          
             End If
          end sub
          
          Sub DelTree(Folder)
             Dim objFolder, file
             ' on error resume next
          
             For Each file in Folder.files
               '# Deleting files in the tree
               '# but.. delete only if olders then .. Days
               If file.datelastmodified < DaysOld then
                 file.delete(Force)
               End If
             Next
          
             For each objFolder in Folder.subfolders
               DelTree objFolder
             Next
          
             With Folder
               '# Deleting Subfolders, starting from the lowest first
               '# Delete folder only if folder is empty
               If (.subfolders.count + .files.count) < 1 then .delete(Force)
             End With
          End Sub
          \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


          • #6
            Re: a script to delete recursively folder with numeric value only with older than cer

            Great !

            the script does works as i expected

            wow I didn't think that complex just to delete the folders, thanks Rams.

            eventhough it reports:
            Microsoft VBScript runtime error: Permission denied
            in the .delete(Force) section but it is serving my needs.

            Cheers.

            Comment


            • #7
              Re: a script to delete recursively folder with numeric value only with older than cer

              Hi Rems,

              Here it is the few modifications that i did to make it better

              thanks to you for the guidance and helps before.


              Code:
              '#############################################################################'
              Set objArgs = WScript.Arguments
              strFolder =objArgs(0)
              intDays=objArgs(1)
              
              Const Force = TRUE
              
              Dim oRegExp, fso, DaysOld, FolderName, baseFolders
              
              Dim startingDirectory, filesOlderThan
              FolderName = strFolder
              filesOlderThan = intDays '(in days)
              
              DaysOld = dateadd("d", -filesOlderThan, now)
              
              set oRegExp = New RegExp: oRegExp.Pattern = "^\d+$"
              set fso = createobject("scripting.filesystemobject")
              set startingDirectory = fso.getfolder(FolderName)
              
              wscript.echo "Today: " & now()
              wscript.echo "*************************************"
              wscript.echo "Started deleting folders older than :" & DaysOld
              wscript.echo "*************************************"
              wscript.echo ""
              
              For each baseFolders in startingDirectory.subfolders
                 Recurse baseFolders
              Next
              
              wscript.echo ""
              wscript.echo "*************************************"
              wscript.echo "Completed"
              wscript.echo "*************************************"
              '============================================================================'
              sub Recurse(Folder)
                 Dim objFolder
              
                 If oRegExp.Test(Folder.name) Then
                   If Folder.datelastmodified < DaysOld Then
              		wscript.echo "Deleting: " & Folder.name
                      DelTree Folder
              	 Else
              		wscript.echo "Skipping: " & Folder.name & " Newer than date:" & DaysOld
              	 End If
                 Else
              	 wscript.echo "Skipping: " & Folder.name
                 End If
              end sub
              '============================================================================'
              Sub DelTree(Folder)
                 Dim objFolder, file
                 
                 For Each file in Folder.files
                     file.delete(Force)
                 Next
              
                 For each objFolder in Folder.subfolders
                   DelTree objFolder
                 Next
                 
                 Folder.delete(Force)
              
              End Sub
              '#############################################################################'

              Comment


              • #8
                Re: a script to delete recursively folder with numeric value only with older than cer

                Originally posted by Albertwt View Post
                Hi Rems,

                Here it is... the few modifications that i did to make it better
                <,,>
                Hi Albertwt,

                Thank you for sharing your script.
                Your script will work great. Best when run under Cscript.exe.


                FYI
                You said you've made a "few modifications", in fact you have removed the recursive function from the recurse sub routine in the new script. Now the 'folder name' and 'folder last modification date' of only the first subfolders (the basefolders) are checked.
                All comparison is now only happen in the first routine and without exploring the data stored further down in a tree structure - therefore it is not really nessesary to call another sub routine just to recursively delete the tree.
                Code:
                '######################################################################'
                Dim objArgs: Set objArgs = WScript.Arguments
                If objArgs.Count <> 2 _
                   then wscript.echo " (!) Wrong number of arguments": wscript.quit
                
                Dim startingDirectory, filesOlderThan
                FolderName = objArgs(0)
                filesOlderThan = objArgs(1) '(in days)
                
                Const Force_Delete = TRUE
                DaysOld = dateadd("d", -filesOlderThan, now)
                
                Dim oRegExp, fso, DaysOld, FolderName, baseFolders
                
                set oRegExp = New RegExp: oRegExp.Pattern = "^\d+$"
                set fso = createobject("scripting.filesystemobject")
                set startingDirectory = fso.getfolder(FolderName)
                
                wscript.echo     "Today:", now() _
                   & vbNewLine & "*************************************" _
                   & vbNewLine & "Started deleting folders..." _
                   & vbNewLine & "older than:", DaysOld _
                   & vbNewLine & "*************************************" _
                   & vbNewLine & vbNewLine
                
                For each baseFolders in startingDirectory.subfolders
                   DelTree baseFolders
                Next
                
                wscript.echo vbNewLine _
                   & vbNewLine & "*************************************" _
                   & vbNewLine & "Completed" _
                   & vbNewLine & "*************************************"
                '======================================================================'
                sub DelTree(Folder)
                   Dim baseFolder
                   On Error Resume Next
                   baseFolder = Folder.name
                   If oRegExp.Test(baseFolder) Then
                
                     If Folder.datelastmodified < DaysOld Then
                       Folder.delete(Force_Delete)
                	     If err.Number <> 0 Then
                	   	   wscript.echo "Skipping:", baseFolder, _
                		           "(!)", err.Description
                	   	   err.Clear
                	     Else
                		     wscript.echo "Deleting: " & baseFolder
                	     End If
                	   Else
                		   wscript.echo "Skipping:", baseFolder, _
                		           "Newer than date:", DaysOld
                	   End If
                
                   Else
                	   wscript.echo "Skipping:", baseFolder
                   End If
                end sub
                '######################################################################'
                \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


                • #9
                  Re: a script to delete recursively folder with numeric value only with older than cer

                  thank you very much Rems,

                  Your script is very-very useful to me

                  Cheers !

                  Comment

                  Working...
                  X