Using Includes in VBScript - Allowing for platform-specific paths
(Page 5 of 6 )
For some people this may be enough, but for me it isn’t. What if I’m using this in a script that passes a path containing environmental variables? Maybe I’m calling a script that resides in the Windows directory like this:
Import "%windir%myscript.vbs"
We can allow for this too. Before the last line of code we added, we can stop and expand any environmental variables using the WSH Shell object’s ExpandEnvironmentStrings method. Don’t forget to create an instance of the WSH Shell object in your subroutine. Now we have this:
Sub Import(strFile)
Set objFs = CreateObject("Scripting.FileSystemObject")
Set WshShell = CreatObject("Wscript.Shell")
strFile = WshShell.ExpandEnvironmentStrings(strFile)
strFile = objFs.GetAbsolutePathName(strFile)
Set objFile = objFs.OpenTextFile(strFile)
strCode = objFile.ReadAll
objFile.Close
ExecuteGlobal strCode
End Sub
Presto! Just like that our subroutine now works with paths containing environmental strings as well. Now I have one more thing to take into consideration. What if I’m using the strFile variable somewhere else in my code and I don’t want it to change?
The way this subroutine is written now, the strFile variable will contained the fully exploded full path to my file when the subroutine finishes. I can prevent this from happening very simply by using the ByVal statement when creating my subroutine.
The ByVal statement will take the strFile attribute (if provided as a variable) by its value. This means that it will not alter the variable’s contents outside of my subroutine’s namespace.
Sub Import(ByVal strFile)
Set objFs = CreateObject("Scripting.FileSystemObject")
Set WshShell = CreateObject("WScript.Shell")
strFile = WshShell.ExpandEnvironmentStrings(strFile)
file = objFs.GetAbsolutePathName(strFile)
Set objFile = objFs.OpenTextFile(strFile)
strCode = objFile.ReadAll
objFile.Close
ExecuteGlobal(strCode)
End Sub
We now have a fully customized subroutine that will allow us to use includes in our script. Let’s put it to the test.
Next: Testing the subroutine >>
More Windows Scripting Articles
More By Nilpo/Developer Shed Staff Writer