How to Create an Environment Variable with AutoIt

May 17, 2009

Windows' environment variables can be created or changed by editing the registry:

  • User environment variables are stored under the key:
    HKEY_CURRENT_USER\Environment
  • System environment variables are stored under the key:
    HKEY_LOCAL_MACHINE
      \SYSTEM
      \CurrentControlSet
      \Control
      \Session Manager
      \Environment
    

Creating an environment variable from AutoIt is as simple as creating a value for the appropriate registry key. For this purpose, the RegWrite AutoIt function must be used. Its signature is:

RegWrite("keyname" [,"valuename", "type", value])

An environment variable created using the above method is not "visible" to other applications until the user logs off and then logs on again. This may not be acceptable in some scenarios but fortunately there is a solution: changes can be propagated to the system by broadcasting a WM_SETTINGCHANGE message to all windows. The AutoIt function to do precisely that is EnvUpdate:

EnvUpdate()

Now that we have all the information we need, let's see some examples.

AutoIt script to create or change a user environment variable:

$result = RegWrite("HKEY_CURRENT_USER\Environment", "USER_TEST_VAR", "REG_SZ", "Test")
If $result = 1 Then
	EnvUpdate()
EndIf

AutoIt script to create or change a system environment variable:

$result = RegWrite("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment",
                    "SYSTEM_TEST_VAR", "REG_SZ", "Test")
If $result = 1 Then
	EnvUpdate()
EndIf

The next image shows the result of running the two previous scripts:

Value of the environment variables set by the previous AutoIt scripts

To set environment variables whose values need to be expanded, the 3rd argument of RegWrite must be REG_EXPAND_SZ instead of REG_SZ, as shown in the next example:

RegWrite("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment",
         "MY_APP_PATH",
         "REG_EXPAND_SZ",
         "%ProgramFiles%\MyApp")

If REG_EXPAND_SZ was not used, the value of the variable MY_APP_PATH would be seen by the system and other applications as %ProgramFiles%\MyApp instead of C:\Program Files\MyApp, i.e. %ProgramFiles% would not be expanded.

Also note that changes made to environment variables do not affect services that run under the Local System account until Windows is restarted. Calling EnvUpdate is no solution for this case.

My previous post shows a real world example of the technique just described.