mistux Site Admin
Joined: 25 Jun 2004 Posts: 1042 Location: South Bend, Indiana USA
|
Posted: Mon Sep 18, 2006 8:31 am Post subject: Search Files and Directories |
|
|
Code: |
'//Author:EvanJHoush
'//Email:evanjhoush (@) hotmail.com
'//Recursive Search and Execute - Files/Folders
'//REQUIRED OBJECT: I create the FS object externally to conserv memory
'// otherwise after many iterations way to many FS objects would be created
Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
'//EXAMPLE USAGE
Set oStartDir = oFSO.GetFolder("c:\test")
sFileRegExPattern = "\.txt$"
sFolderRegExPattern = "Program\sFiles$"
sCMDFile = "wscript.echo(oFile.Name)"
sCMDFolder = "bSkip = True : wscript.echo(oSubFolder.Path)"
RecurseFilesAndFolders oStartDir, sFileRegExPattern , sCMDFile, sFolderRegExPattern , sCMDFolder
'//END EXAMPLE
Sub RecurseFilesAndFolders(oRoot, sFileEval, sFileExec, sFolderEval, sFolderExec)
'//[oRoot] as Folder Object
'//[sFileEval] as RegExp Pattern to test against
'//the Name property of the File object.
'//[sFileExec] as string of Code to execute for each file --
'//Reference the file using oFile as the object name, (dot"."),
'//then the file object property EX.."wscript.echo(oFile.Name)"
'//[sFolderEval] as RegExp Pattern to test against
'//the Name property of the Folder object.
'//[sFolderExec] as string of Code to execute for each folder --
'//Reference the folder using oFolder as the object name, (dot"."),
'//then the folder object property EX.."wscript.echo(oSubFolder.Path)"
'//You can also set the variable bSkip = True to not recurse down a certain dir
Dim oSubFolder, oFile, oRegExp, bSkip
Set oRegExp = New RegExp '//create the Regular Expression Object
oRegExp.IgnoreCase = True '//Set it to ignore the case of characters - Reduces the complexity of the search string.
If Not (sFileEval = "") Then '//Check to see if a search string was passed for files.
oRegExp.Pattern = sFileEval '//set the search string as the RE pattern
For Each oFile in oRoot.Files '//Loop through the files in the dir.
If (oRegExp.Test(oFile.Name)) Then '//check that they match the search pattern
Execute sFileExec '//Run the code string we passed in for the files.
End If
Next
End If
For Each oSubFolder In oRoot.SubFolders
bSkip = False
If Not (sFolderEval = "") Then '//Check to see if a search string was passed for folders.
oRegExp.Pattern = sFolderEval '//set the search string as the RE pattern
If (oRegExp.Test(oSubFolder.Name)) Then '//Check if folder name matches pattern
Execute sFolderExec '//Run code for folders that match pattern
End If
End If
If Not bSkip Then RecurseFilesAndFolders oSubFolder, sFileEval, sFileExec, sFolderEval, sFolderExec '//Call this sub again to recurse down to the next level
Next
End Sub
|
|
|