首页 > 解决方案 > 使用 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

标签: vbscript

解决方案


您的递归永远不会因此而终止:

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

您可能还想调整递归过程内部的条件,因为它使用objFileobjFolder定义在过程之外。


推荐阅读