VBScript递归子程序内存泄漏问题求助(文件搜索CSV场景)
解决VBScript递归搜索内存耗尽问题并优化CSV输出
首先,咱们来拆解你遇到的内存耗尽问题——核心原因是你的递归子程序ShowSubFolder犯了一个关键错误:它一直在遍历根文件夹的子文件夹集合(全局的colFolders),而不是当前传入的子文件夹的子目录。这会导致无限递归调用同一个子文件夹,最终撑爆栈内存。除此之外,代码里还有几个其他问题会导致报错或输出异常,我一起帮你修正:
原代码的主要问题
- 递归逻辑错误:使用全局的
colFolders而非当前子文件夹的子目录集合,引发无限递归 - 变量作用域错误:递归函数中未定义
objFile就直接引用 - CSV格式不规范:未处理文件名含逗号的情况,会破坏CSV结构
- 路径拼接错误:手动拼接路径会导致缺失分隔符,直接用
objFile.Path更可靠 - 边界情况未处理:用户取消输入框、文件创建失败等场景没有容错
修正后的完整代码
Option Explicit ' 强制变量声明,避免隐式错误 Dim fileCount, searchPath, searchTerm, savePath Dim objFSO, objFolder, objFile, objWriteFile Const ForWriting = 2 ' 定义CSV保存路径 savePath = "C:\Users\USERFILE\Desktop\Audit.csv" Set objFSO = CreateObject("Scripting.FileSystemObject") ' 获取搜索路径,处理用户取消的情况 searchPath = InputBox("Please enter the path of the folder you would like to search", "Where am I searching?") If searchPath = "" Then WScript.Echo "You didn't enter a search path. Exiting." WScript.Quit End If ' 验证路径是否存在 If Not objFSO.FolderExists(searchPath) Then WScript.Echo "The specified path does not exist. Exiting." WScript.Quit End If Set objFolder = objFSO.GetFolder(searchPath) ' 获取搜索关键词,处理用户取消的情况 searchTerm = InputBox("Please enter the term you would like to search for", "What am I searching?") If searchTerm = "" Then WScript.Echo "You didn't enter a search term. Exiting." WScript.Quit End If ' 检查CSV文件是否存在 If objFSO.FileExists(savePath) Then WScript.Echo "Please delete the file named Audit.csv before trying again" WScript.Quit End If ' 创建CSV文件并写入表头 Set objWriteFile = objFSO.CreateTextFile(savePath, ForWriting, True) objWriteFile.Writeline """Filename"", ""File Size (Bytes)"", ""Last Modified Date"", ""Absolute Path""" ' 开始搜索根文件夹和子文件夹 SearchFolder objFolder ' 关闭文件并提示完成 objWriteFile.Close WScript.Echo "Search completed. Results saved to " & savePath ' 递归搜索文件夹的核心子程序 Sub SearchFolder(Folder) Dim objSubFolder, currentFile ' 搜索当前文件夹下的文件 For Each currentFile In Folder.Files ' 不区分大小写匹配文件名 If InStr(LCase(objFSO.GetFileName(currentFile)), LCase(searchTerm)) > 0 Then ' 用引号包裹字段,处理含逗号的文件名 objWriteFile.Write """" & objFSO.GetFileName(currentFile) & """, " objWriteFile.Write """" & currentFile.Size & """, " objWriteFile.Write """" & currentFile.DateLastModified & """, " objWriteFile.Write """" & currentFile.Path & """" objWriteFile.Writeline End If Next ' 递归搜索子文件夹 For Each objSubFolder In Folder.SubFolders SearchFolder objSubFolder Next End Sub
关键修改说明
- 修复递归逻辑:
SearchFolder子程序现在遍历传入的Folder对象的子文件夹,而不是全局的根文件夹子目录,彻底解决无限递归导致的内存耗尽问题 - 添加变量声明:使用
Option Explicit强制变量声明,避免隐式变量错误 - 规范CSV输出:所有字段用双引号包裹,确保文件名含逗号时不会破坏CSV结构
- 优化路径获取:直接使用
currentFile.Path获取文件绝对路径,避免手动拼接的错误 - 增加边界处理:检查用户是否取消输入框、路径是否存在,提升脚本健壮性
- 添加CSV表头:让输出的CSV更易读
内容的提问来源于stack exchange,提问作者hidonor
相关产品推荐
相关产品推荐

