且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

删除子文件夹中文件的VB脚本

更新时间:2023-12-05 19:03:46

从遍历文件夹树的骨架脚本开始:

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

输出:

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

Main 函数将一个文件夹和一个 worker 传递给 traverseDir 函数并返回要传递给调用者 (OS) 的退出代码.traverseDir函数将目录中的每个文件发送到 worker 的 processFile 子,调用递归地为每个子文件夹返回一个错误代码调用者(自身的主要/上一个实例).(琐碎的)工人只是回应文件的路径.

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 使用具有硬编码条件的工作器来确定哪个要删除的文件:

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

输出:

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

基于此概念验证脚本,您可以增强 traverseDir 功能(对不可访问的文件夹的错误处理,...)和/或 cWorker 类(更多复杂条件、错误处理、日志记录……).

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, ...).

更新:

请参阅此递归文件夹访问脚本,了解进一步增强骨架的想法.

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