There are various ways to do this. The approach discussed here uses Windows Scripting Host (WSH) and probably offers the least amount of resistance and the most bang for the buck.

All Windows OSes with the exception of Windows 95 (I think) come with WSH pre-installed. And if you need it for Windows 95, you could download it from the Microsoft site.

To display the version of WSH installed on Windows, type cscript at the command prompt and then press ENTER. It should display an output like the following:

C:\Documents and Settings\xxxx>cscript
Microsoft (R) Windows Script Host Version 5.7
Copyright (C) Microsoft Corporation. All rights reserved.

Usage: CScript scriptname.extension [option...] [arguments...]

Options:
//B Batch mode: Suppresses script errors and prompts from displaying
//D Enable Active Debugging

To read more about WSH: http://www.microsoft.com/technet/scriptcenter/guide/sas_wsh_overview.mspx

Enough talk. Let’s see an example script that sets an environment variable (say, ”environSet.vbs”):

'Set JAVA_HOME, JRE_HOME and update PATH
set shellObj = WScript.CreateObject("WScript.Shell")
set envObj = shellObj.Environment("System")
envObj("JAVA_HOME")="C:\tools\jdk\jdk1.6.0_10"
envObj("JRE_HOME")="C:\tools\jdk\jdk1.6.0_10\jre"
envObj("PATH")=envObj("PATH") & ";%JAVA_HOME%\bin;%JAVA_HOME%\jre\bin\client"

To run the above script, you can open a command shell, type cscript environSet.vbs (or just environSet.vbs) and press ENTER or just double-click the environSet.vbs file.

In the above example, the JAVA_HOME and JRE_HOME system environment variables are set to “c:\tools\jdk\jdk1.6.0_10″ and “c:\tools\jdk\jdk1.6.0_10\jre” respectively. The PATH system environment variable is updated and appended with “%JAVA_HOME%\bin;%JAVA_HOME%\jre\bin\client”.

Notes:

  • If the variables do not exist, they are created. If they already exist, they will be over-written unless you take care to append them as shown in the above example (see PATH)
  • When you run the above script, the updates are also reflected in the registry. In the above case since we have set the System environment variables you could browse to HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment\ in regedit to see the system environment variables.
  • Some pre-defined system variables such as PATH may not be picked by Windows services and will require a Windows Reboot.