vbscript - 使用 VBScript 的递归子内存泄漏
问题描述
我正在创建一个脚本,该脚本将允许用户使用搜索词在指定目录中进行搜索。该脚本将创建一个 CSV 文件,然后写入基本文件名、文件大小、最后修改日期以及文件名中包含搜索词的文件的绝对路径。但是,我在搜索文件夹中的子文件夹时遇到了问题。问题是我在子例程中的内存不足。
这是我迄今为止编写的脚本。
Dim fileCount, searchPath, searchTerm, CheckFile, wholePath
Dim objFSO, objFolder, objFile, objWriteFile
Dim savePath
objCheckFile = "C:\Users\USERFILE\Desktop\Audit.csv"
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Asks for directory to search in
searchPath = InputBox("Please enter the path of the folder you would like to search", "Where am I searching?")
Set objFolder = objFSO.GetFolder(searchPath)
'Asks for the search term to use
searchTerm = InputBox("Please enter the term you would like to search for", "What am I searching?")
If objFSO.FileExists(objCheckFile) Then
WScript.Echo "Please delete the file named Audit.csv before trying again"
Else
Set objWriteFile = objFSO.CreateTextFile("Audit.csv", ForWriting, True)
End If
Set colFiles = objFolder.Files
Set colFolders = objFolder.SubFolders
'Searches for files within the folder and writes to a CSV file
For Each objFile In colFiles
If InStr(LCase(objFSO.GetFileName(objFile)), LCase(searchTerm)) > 0 Then
objWriteFile.Write objFSO.getFileName(objFile) & ", "
objWriteFile.Write objFile.size & ", "
objWriteFile.Write objFile.DateLastModified & ", "
objWriteFile.Write objFSO.getAbsolutePathName(objFolder) & objFSO.getFileName(objFile)
objWriteFile.Writeline
End If
Next
ShowSubFolder objFolder
Sub ShowSubFolder(Folder)
If InStr(LCase(objFSO.GetFileName(objFile)), LCase(searchTerm)) > 0 Then
objWriteFile.Write objFSO.getFileName(objFile) & ", "
objWriteFile.Write objFile.size & ", "
objWriteFile.Write objFile.DateLastModified & ", "
objWriteFile.Write objFSO.getAbsolutePathName(objFolder) & objFSO.getFileName(objFile)
objWriteFile.Writeline
End If
For Each objSubFolder In colFolders
ShowSubFolder objSubFolder
Next
End Sub
解决方案
您的递归永远不会因此而终止:
Set colFiles = objFolder.Files
Set colFolders = objFolder.SubFolders
'...
ShowSubFolder objFolder
Sub ShowSubFolder(Folder)
'...
For Each objSubFolder In colFolders
ShowSubFolder objSubFolder
Next
End Sub
这类似于叉形炸弹。对于objFolder
您的每个子文件夹,再次递归到objFolder
. 然后再次。然后再次。和 ...
将您的代码更改为此,它应该执行您想要的操作:
Set colFiles = objFolder.Files
'...
ShowSubFolder objFolder
Sub ShowSubFolder(Folder)
'...
For Each objSubFolder In Folder.SubFolders
ShowSubFolder objSubFolder
Next
End Sub
您可能还想调整递归过程内部的条件,因为它使用objFile
和objFolder
定义在过程之外。
推荐阅读
- python - VS Code 中的 Pytorch:torch.tensor 不可调用
- reactjs - TypeError:类别未定义
- java - 将 Hazelcast 3.5.* 升级到更新版本而不会丢失数据
- java - 创建具有多个键和值的哈希图的多个 LinkedLists 的最佳方法?
- sql-server - Databricks 增量表与 SQL Server 增量表
- reactjs - 在 Mac 上将 UI (react.js) 打印为 PDF 已损坏
- keras - keras.backend 的 prod、cast 和 shape 功能是什么?
- sql - 用于比较 2 个主机 URL 的 SQL 查询
- python - 从 Django/Python 中的日期时间字段中减去时间
- machine-learning - 需要对缺失值的统计表达式进行解释