“Wrapping” an executable with session environment variables in a script can be used as a basic way to make an executable portable. For example, if the executable depends on a system environment variable, such as
%PATH%, the script passes a session PATH variable, to tell the executable where to look for its dependencies, without actually modifying the system
PATH. Similarly, if the executable writes to some directory, such as
%TEMP%, setting session environment variables can redirect the executable’s output (e.g., temporary files).
I will use LONI’s ShapeViewer tool as an example. It is an executable java jar requiring Java 1.6+ and the Java 3D library. Installing the Java 3D library can be annoying, particularly because extra files need to be inserted into the system Java installation. This is sometimes not possible on a loaned laptop or a computer without admin rights to modify the Java installation.
A three-line batch file solves this problem. This assumes that some Java directory has already been prepared with Java 3D files. In this case, this Java directory is in a directory a couple times up the directory tree containing ShapeViewer.jar.
@echo off set PATH=%CD%\..\..\Java\bin java -jar ShapeViewer.jar
This works very well, except that it leaves a Windows command line console open. This can also be slightly annoying (e.g. if I’m working on a small laptop screen). Using
javaw doesn’t seem to help in this case (
javaw is supposed to be equivalent to running java, but without a console window).
Another script in VBScript solves this problem, by calling the batch file above. The zero argument after
objShell.Run hides the console window.
' References ' 1. http://stackoverflow.com/questions/6941167/hiding-a-simple-batch-window/6941198#6941198 Set objShell = WScript.CreateObject("WScript.Shell") objShell.Run("ShapeViewerPortable.bat"), 0, True
But can we avoid having two separate scripts (especially since they’re each a couple lines long)? It turns out that you can set a session environmental variable in VBScript, then run the executable.
' References ' 1. http://wsh2.uw.hu/ch07c.html Set WshShell = CreateObject("WScript.Shell") Set objEnv = WshShell.Environment("Process") objEnv("PATH") = "D:\Portable\Java\bin" WshShell.Run("java -jar ShapeViewer.jar"), 0, True
Interestingly, relative paths don’t work in
PATH. Also note that environmental variables after Windows 98 can also be categorized, in addition to Process, as System, User, and Volatile. So it is also possible to modify a system environmental variable from a VBScript (which would probably require admin rights).