Using Includes in VBScript - Allowing for relative or absolute path names
(Page 4 of 6 )
First things first, I want this code to work with either absolute or relative file paths. To do that, we’re going to add a single line before trying to open the input file.
Sub Import(strFile)
Set objFs = CreateObject("Scripting.FileSystemObject")
strFile = objFs.GetAbsolutePathName(strFile)
Set objFile = objFs.OpenTextFile(strFile)
strCode = objFile.ReadAll
objFile.Close
ExecuteGlobal strCode
End Sub
In this line, I use the FileSystemObject’s GetAbsolutePathName to reassign the strFile variable with a full path to the file to be included. What’s nice is how the GetAbsolutePathName works in this particular case.
If you are using a script editor with a debugger to test this script, it may fail at this point. This is because most debuggers will not execute your code from the directory where your script resides. If this happens, try hard coding a path while testing your script.
The GetAbsolutePathName method will return a text string containing a full file path. If a full path is not supplied to it, it will create one by assuming the partial path is relative to the script’s execution directory. Here’s what that means.
If we supply only a filename, it will assume the file resides in the same directory as our script and return a full path to that file. If we supply something like “includesmyinclude.vbs”, it will assume that the “includes” directory resides in the same directory as our script and return a full path accordingly.
Next: Allowing for platform-specific paths >>
More Windows Scripting Articles
More By Nilpo/Developer Shed Staff Writer