At the top of most of my VBscripts (.vbs files) I have the following code:
Option Explicit
Const ForReading = 1
Dim objFSO, objFile
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("Z:\somepath\somefile.vbs", ForReading)
Execute objFile.ReadAll()
This code allows me to use another vbs file as a library. In this case somefile.vbs
would be my library and have all my subs and functions defined that are called from the script the above code is called from (I call this the calling script).
This issue: Every once in a while, one of the scripts seems to delete the code in Z:\somepath\somefile.vbs
(the library script read by the calling script).
I think this because if a wscript.exe
is listed in my Task Manager Processes tab and I restore the Z:\somepath\somefile.vbs
file from a backup location, almost immediately, when I open Z:\somepath\somefile.vbs
again, there is no code in that file. But if I kill the wscript.exe
process, the file is fine. I can't reproduce the behavior because it only occurs when our network has a hiccup of some kind (I think).
My first thought is that the create
setting is wrong when I use this line:
Set objFile = objFSO.OpenTextFile("Z:\somepath\somefile.vbs", ForReading)
But according to this link, the default create
value should be false:
https://msdn.microsoft.com/en-us/library/aa265347(v=vs.60).aspx
Note, coincidentally, I am also using objFile
and objFSO
variables in the file somefile.vbs
for things that aren't related to what I am doing in the calling script. For example, the objFile
in the somefile.vbs
file has a completely different name and location and is created this way:
Set objFile = objFSO.OpenTextFile("z:\differentpath\differentname.vbs", ForAppending, True)
I am guessing this is the issue, but I don't understand it. Can someone shed some light on this? Is the create
or append
setting getting reset in the calling script? How does that work?
Not knowing what else to do I have change the variable names in the somefile.vbs
file to oFSO, oFile
and in the calling script they are still objFSO, objFile
. I also changed the line of code in the calling script to include false
for the create
setting like this:
Set objFile = objFSO.OpenTextFile("Z:\somepath\somefile.vbs", ForReading,false)
Going out on a limb (since you posted only partial code) I'm going to assume that you don't explicitly close your library script after reading, so your main script keeps the file open until it terminates. Either add a line objFile.Close
after the Execute
statement, or (better yet) change
Set objFile = objFSO.OpenTextFile("Z:\somepath\somefile.vbs", ForReading)
Execute objFile.ReadAll()
to
code = objFSO.OpenTextFile("Z:\somepath\somefile.vbs").ReadAll
Execute code
or just
Execute objFSO.OpenTextFile("Z:\somepath\somefile.vbs").ReadAll
so that the file is automatically closed after being read.