Determine a Script's Path On the Fly

The ScriptPath function determines a script's path while the script is running so that the script can, for example, use a .wsc file that's not registered on the computer.

Bill Stewart

March 12, 2006

2 Min Read
ITPro Today logo in a gray background | ITPro Today


It's sometimes useful to determine a script's path while the script is running. To accomplish this, I wrote the ScriptPath function in both VBScript and JScript. Listing 1 shows the VBScript version of the function. Listing 2 shows the JScript version.

There isn't a Windows Script Host (WSH) property that returns just the currently running script's path, so the ScriptPath function includes some creative coding with the WScript object's ScriptFullName and Script-Name properties. ScriptFullName returns the full path and filename of the current script. ScriptName returns just the script's filename. To obtain only the script's path, the ScriptPath function returns the ScriptFullName property less the number of characters in the filename returned by the ScriptName property. The VBScript version uses the Left function and the JScript version uses the substr method for this task. The ScriptPath function leaves the trailing backslash () character at the end of the path.

One use for the ScriptPath function is if you have a script that creates a log file and you want to write the log file to the same directory as the script. Another example is if you have a script component (e.g., a .wsc file) that you want to use without registering it on the computer. In VBScript and JScript, you can create a reference to a script component's object using the GetObject function and use

script:pathcomponent.wsc 

as the parameter, where path is the directory containing the component and component.wsc is the component's filename. The drawback to this syntax is that you must specify the full path to the component file. You can work around this limitation by using the ScriptPath function if the component file is in the same directory as the script. For example, if the file MyObject.wsc is in the same directory as your script, you can use the VBScript code

Set MyObject = _   GetObject("script:" & _  ScriptPath() & _   "MyObject.wsc") 

to retrieve the object reference. The equivalent JScript code is

myobject = GetObject("script:"   + ScriptPath()  + "MyObject.wsc");
Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like