Include External Files in VBScript/JScript (WSH)


Under Windows Script Hosting WSH, the language of VBScript or JScript do not provide built-in keyword to support importing external script files (*.vbs or *.js). This is not very convenient if you have some common functions defined which are used in many files.

The workaround is using Scripting.FileSystemObject to read the script files as text string and execute it. In VBScript, there are built-in functions Execute and ExecuteGlobal. The Execute method only runs at the scope of the function that uses it which is include. In order to make it “global”, use ExecuteGlobal which specifies the global namespace and doesn’t use local variables. In Javascript, the eval function is equivalent to the Execute in VBScript. However, to make it global, you have to place the eval function where you want to include the file.

Function Include(vbsFile)
    Dim fso, f, s
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set f = fso.OpenTextFile(vbsFile)
    s = f.ReadAll()
    f.Close 
    ExecuteGlobal s
End Function

Include "File.vbs"

Here is the JavaScript version.

function Include(jsFile) 
{
    var fso, f, s;
    fso = new ActiveXObject("Scripting.FileSystemObject"); 
    f = fso.OpenTextFile(jsFile); 
    s = f.ReadAll(); 
    f.Close(); 
    return(s); 
}

eval(Include("File.js"));

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
285 words
Last Post: Tricks of VBScript
Next Post: Separate the Logics from the Presentation

The Permanent URL is: Include External Files in VBScript/JScript (WSH)

Leave a Reply