Thursday, August 14, 2008
How to modularize vbscripts and make a script library
Wouldn't it be nice to load vb scripts at run time? With the following code you can load any text file at run time.
I call this function LoadScript. The idea is to simply call LoadScript at the beginning of each program that needs to load a script like this:
LoadScript "adoconst.txt"
LoadScript "fso_lib.vbs"
LoadScript "sql_lib.vbs"
etc....
It works kind of like Java import statements. Of course you can call the function what ever you want so if you want to call it Import and use it like this:
Import "adoconst.txt"
Import "fso_lib.vbs"
Import "sql_lib.vbs"
That works just as well.
Here is the function.
Sub LoadScript(p_file_name)
Dim fso, f, ws_shell, ws_env
Dim code
'get the path to your script library
set ws_shell = CreateObject("WScript.Shell")
set ws_env = ws_shell.Environment("SYSTEM")
p_file_name = ws_env("SCRIPT_LIB_DIR") & "\" & p_file_name
'open up the script file
set fso = CreateObject("Scripting.FileSystemObject")
set f = fso.OpenTextFile(p_file_name, 1) ' 1 means ForReading
code = f.ReadAll()
f.Close
'This places your code in the global scope
'so it is available everywhere in your script
ExecuteGlobal code
'clean up
set ws_shell = nothing
set ws_env = nothing
set f = nothing
set fso = nothing
End Sub
One last thing to do.
Open Control Panel.
Then Open System.
Click on Advanced System Settings.
Click on Environment Variables.
Click on New under System Variables.
Name the new variable SCRIPT_LIB_DIR
Then give it the path to your script library
The environment variable makes LoadScript more robust and easier to use. Now you can place all your vbscript modules in one directory and load them by using the LoadScript sub routine. Just place the LoadScript function in any script that needs to use another vbscript module and load your scripts.
Subscribe to:
Post Comments (Atom)
1 comments:
Good for people to know.
Post a Comment