views:

124

answers:

3

I maintain a good number of vbscripts for performing various startup scripts on my network and have a handful of functions that I use in almost all of them.

Short of copy and paste, does anyone have suggestions for how I can go about creating libraries of reusable vbscript code. I'm not averse to using a code generator for doing so as long as it isn't more of a headache than copy and paste is. But any recommendations would be appreciated.

Thanks

+6  A: 

VBScript has the Execute statement, so if you don't want to go the WSF route Tester101 proposes, you can do an include like this:

Set fso = CreateObject("Scripting.FileSystemObject")
file = "your_library.vbs"

Execute fso.OpenTextFile(file, 1).ReadAll

Set foo = New FooClass
MsgBox foo.GetBar()

Assuming "your_library.vbs" would contain a class definition for FooClass.

Be sure to call Execute in global context, or you will get into scoping issues.

Of course be sure to have all your files under tight control to prevent malicious usage.

Tomalak
So "your_library.vbs" has to contain a class definition, not just a collection of routines?
Tester101
@Tester101: In fact you can put anything in the file. The class was just an example, functions and subs will work the same.
Tomalak
I love this approach, since it doesn't force you to use WSH. In my situation I am however, but still neat to know.
Allain Lalonde
+2  A: 

I use a synthetic include (as below) and store my libraries in a subdirectory.

Sub Include( scriptName )
    Dim sScript
    Dim oStream
    With CreateObject( "Scripting.FileSystemobject" )
 Set oStream = .OpenTextFile( scriptName )
    End With
    sScript = oStream.ReadAll()
    oStream.Close
    ExecuteGlobal sScript
End Sub

Obviously, if there's an error in the included script, you're not going to get a very helpful error message (VBScript won't be able to tell you what line the problem occurred on.) Once everything works, however ...

Include "c:\script\stdlib.vbs"
Include "c:\script\INI.cls"
boost
+1 For ExecuteGlobal
Allain Lalonde