Using Includes in VBScript - Executing the external code
(Page 3 of 6 )
There are a couple of ways to execute code dynamically in VBS. Basically, this means that VBS will interpret a text input and execute it as if it were hard coded into the script. I’m only going to focus on the method that we need in this particular instance.
ExecuteGlobal textinput
The ExecuteGlobal statement accepts a single text string input. The code is then executed in the global namespace. Why have I chosen to execute it globally? The answer is very simple. I’m calling this method from within a subroutine and I want any contained variables or returns to be available in my script at the point where my subroutine was called.
The Execute and ExecuteGlobal statements aren’t very well documented. Both accept a single string input that contains one or more statements to be executed. The ExecuteGlobal statement executes the code in the global namespace while the Execute statement executes code locally.
All we need to do now is add an ExecuteGlobal statement to our subroutine and supply it with the contents of our strCode variable. Our final subroutine looks like this:
Sub Import(strFile)
Set objFs = CreateObject("Scripting.FileSystemObject")
Set objFile = objFs.OpenTextFile(strFile)
strCode = objFile.ReadAll
objFile.Close
ExecuteGlobal strCode
End Sub
Well, that was simple enough. We now have a working subroutine that can emulate includes in VBScript. Just add your subroutine to the end of your script file and make calls like the following anywhere that you need an include.
Import "C:myinclude.vbs"
Myinclude.vbs can be any valid script file that you wish to use.
Of course, if you know me at all by now, we’re not done with this code. We need to add some flexibility to it. We’ll do that in the next section.
Next: Allowing for relative or absolute path names >>
More Windows Scripting Articles
More By Nilpo/Developer Shed Staff Writer