VBScript to Delete files in subfolder

后端 未结 1 856
甜味超标
甜味超标 2020-12-22 06:15

I am in need of VB Script to delete unnecessary / unwanted files (with different extension, but last name of files are common such as ABC123DEF.pdf, ABC456DEF.pdf, QWE145_so

相关标签:
1条回答
  • 2020-12-22 07:00

    Start with a skeleton script that traverses a folder tree:

    Step00.vbs:
    
    Option Explicit
    
    Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject")
    
    WScript.Quit Main()
    
    Function Main()
      Dim sDir : sDir = "..\test"
      Dim oWorker : Set oWorker = New cWorker
      Main = traverseDir(goFS.GetFolder(sDir), oWorker)
    End Function
    
    Class cWorker
      Public Sub processFile(oFile)
        WScript.Echo oFile.Path
      End Sub
    End Class
    
    Function traverseDir(oDir, oWorker)
      traverseDir = 0
      Dim oF
      For Each oF In oDir.Files
          oWorker.processFile oF
      Next
      For Each oF In oDir.SubFolders
          traverseDir = traverseDir(oF, oWorker)
      Next
    End Function
    

    Output:

    cscript step00.vbs
    E:\trials\SoTrials\answers\13415663\test\13415663.notes
    E:\trials\SoTrials\answers\13415663\test\13415663.kpf
    E:\trials\SoTrials\answers\13415663\test\13415663-UE15.prj
    E:\trials\SoTrials\answers\13415663\test\vbs\step00.vbs
    

    The Main function passes a folder and a worker to the traverseDir function and returns an exit code to be passed to the caller (OS). The traverseDir function sends each file in a directory to the worker's processFile sub, call itself recursively for each subfolder, and returns an error code to the caller (Main/previous instance of itself). The (trivial) worker just echos the file's path.

    Step01.vbs uses a worker with a hardcoded condition to determine which files to delete:

    Class cWorker
      Public Sub processFile(oFile)
        If "notes" = goFS.GetExtensionName(oFile.Name) Then
           WScript.Echo "will delete", oFile.Path
           oFile.Delete
        End If
      End Sub
    End Class
    

    output:

    cscript step01.vbs
    will delete E:\trials\SoTrials\answers\13415663\test\13415663.notes
    

    Based on this proof of concept script you can enhance the traverseDir function (error handling for not accessible folders, ...) and/or the cWorker class (more complex condition, error handling, logging, ...).

    Update:

    See this recursive folder access script to get ideas for further enhancements of the skeleton.

    0 讨论(0)
提交回复
热议问题