How to include a file from within a VBScript script

VBScript 5.6 does not provide a statement to include files. But the ExecuteGlobal statement can be used to include program code from a file. The test program below shows how to do it.

Example of how to call the test program:

cscript TestIncludeFile.vbs

File TestIncludeFile.vbs.zip




' Test program for the IncludeFile and ReadConfigFile functions.
' Author: Christian d'Heureuse (www.source-code.biz)

Option Explicit

Dim fso: set fso = CreateObject("Scripting.FileSystemObject")

' Includes a file in the global namespace of the current script.
' The file can contain any VBScript source code.
' The path of the file name must be specified relative to the
' directory of the main script file.
Private Sub IncludeFile (ByVal RelativeFileName)
Dim ScriptDir: ScriptDir = fso.GetParentFolderName(WScript.ScriptFullName)
Dim FileName: FileName = fso.BuildPath(ScriptDir,RelativeFileName)
IncludeFileAbs FileName
End Sub

' Includes a file in the global namespace of the current script.
' The file can contain any VBScript source code.
' The path of the file name must be specified absolute (or
' relative to the current directory).
Private Sub IncludeFileAbs (ByVal FileName)
Const ForReading = 1
Dim f: set f = fso.OpenTextFile(FileName,ForReading)
Dim s: s = f.ReadAll()
ExecuteGlobal s
End Sub

' Includes the configuration file.
' The configiguration file has the name of the main script
' with the extension ".config".
Private Sub ReadConfigFile
Dim ConfigFileName: ConfigFileName = fso.GetBaseName(WScript.ScriptName) & ".config"
IncludeFile ConfigFileName
End Sub

ReadConfigFile

WScript.Echo "ConfigParm1=" & ConfigParm1
WScript.Echo "ConfigParm2=" & ConfigParm2
Sub1



File TestIncludeFile.config

' This is a sample configuration file.

Const ConfigParm1 = 123
Const ConfigParm2 = "Hello"

' Normally no subroutines would be located within a
' configuration file.
' This is just to demonstrate that it is possible.
Sub Sub1()
WScript.Echo "Sub1 running"
End Sub



Note for JScript

Daniel Vorhauer (hexerei-software.de) sent me a note about the same problem in JScript. In JScript there is no ExecuteGlobal function as in VBScript. But the same effect can be achieved by calling the eval() function within the global scope.

Example:

var fso = new ActiveXObject("Scripting.FileSystemObject");
eval(fso.OpenTextFile("test.js",1).ReadAll());



Author: Christian d'Heureuse (www.source-code.biz, www.inventec.ch/chdh)
License: Free / LGPL
Index