In VBScript, how do I manage "Scripting.FileSystemObjects" like objFSO and objFolder for multiple folders/files ?
In the "Main" code section, I declare an instance (global) of "Scripting.FileSystemObject"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Then, I perform some operations, like:
If objFSO.FileExists(strOutputFilename) Then
WScript.Echo "Deleting File: " & strOutputFilename
objFSO.DeleteFile strOutputFilename
End If
Then, in a loop, I get a folder, and pass it to a function:
For gintLoop = 0 to (ubound(arraySearchPath))
wscript.echo "Processing folder:" & arraySearchPath(gintLoop)
Set objFolderX = objFSO.GetFolder(arraySearchPath(gintLoop))
Call DoWork (objFolderX, arrayParam1, arrayParam2)
Next
So far everything is clear...
Now, within the function, I do things like:
a) collect filenames from objFolder
Set lobjFolder = objFSO.GetFolder(objFolderX.Path)
Set lcolFiles = lobjFolder.Files
b) check for existance of files in other (unrelated) paths
c) get the size of various files:
lcurInputFileSize = CCur(lobjFile.Size)
d) delete various files
e) open files for reading
For Each lobjFile in lcolFiles
lstrTargetFile = lobjFolder.Path & "\" & lobjFile.Name
Set lobjInputFile = objFSO.OpenTextFile(lstrTargetFile, ForReading)
...
f) open files for writing
Set lobjOutputFile = objFSO.OpenTextFile(strOutputFilename, ForAppending, True)
g) call other subs/functions passing various object
h) recursively call the (same) function to process other folders
For Each lobjSubfolderY in objFolderX.SubFolders
Call DoWork (lobjSubfolderY, arrayParam1, arrayParam2)
Next
My concern is that I need to make sure the various uses of FileSystemObjects like folder paths, open files, etc, are not "Stepped-on" by later uses of FileSystemObjects.
Question 1: Do I need (or is it advised) to have a seperate instance of "Scripting.FileSystemObject" (objFSO) for "Main" and each (or some) sub/function ?
Question 2: Similarly, how do I manage the various other objects to avoid loosing data ?
Kevin
Q1: No, you do not need multiple instances of Scripting.FileSystemObject.
The methods on the object are all static.
In fact, the documentation for the Scripting Runtime Reference indicates that the FSO is a singleton, although it does not use the word:
You can create only one instance of the FileSystemObject object, regardless of how many times you try to create another.
from: http://msdn.microsoft.com/en-us/library/2z9ffy99(v=vs.84).aspx
In my experience, calling WScript.CreateObject("Scripting.FileSystemObject")
multiple times does not result in an error. Likely the return value on subsequent calls is just a copy of the originally created FSO.
As for your Question 2, I don't get it. I think you are referring to objects that are returned by FSO, objects of type Folder, File, TextStream and so on.
Treat these like any other stateful object. You can have multiple instances, and you need to pass them as stack-based arguments if you want to do recursion.