Windows – Using *.reg files for defining Environment variable on windows

environment-variableswindowswindows-registry

I am preparing a set of instructions for automating an installation of some application on our team's computers and as part of that automation I need to add User Environment Variables and System Environment Variables. We are using both Windows XP and Windows 7

I wanted to do it using a *.reg file that will add these variables. So I have several questions:

Is the following correct for User Environment Variables:

[HKEY_CURRENT_USER\Environment]
"TEST"="ABC"'

Is the following correct for System Environment Variables:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment]
"TEST2"="XYZ"'

What is the difference between:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment]
and
[HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Environment]

I want to update the PATH environment variable, can I do something like:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment]
"PATH"="C:\temp\;%PATH%"'

Thanks.

Best Answer

You're basically right re: the user and computer environment locations. If you create values of type REG_SZ Windows will refuse to "expand" other environment variables you might reference in them (i.e. "FOO"="%OTHER_VAR%\bar" as a REG_SZ will create an environment variable FOO with the literal string "%OTHER_VAR%\bar" as its value). Creating values as REG_EXPAND type will cause Windows to expand the variables. It's a quirky behavior because and REG_EXPAND types aren't actually "expanded" by the registry APIs.

"CurrentControlSet" is a symlink to the ControlSetXXX instance being used. If you boot with a different hardware profile you'll get a different "CurrentControlSet". This mechanism can be loosely thought of similiar to different runlevels in an inittab if you're familiar with SYSV *nix.

To demonstrate that "CurrentControlSet" is really a symlink just create a new key under "HKLM\System\CurrentControlSet" and go look for it under "...\ControlSet001". You'll find it there.

Finally, what you want to do w/ adding-on to the PATH variable won't work. You can't have multiple registry values in the same key with the same name. If you create a value named "PATH" then there will be no "%PATH%" for the new "PATH" to expand. Appending to the PATH is a real shortcoming of how the path is stored in the registry. You're going to have to append a string to the "PATH" value and, if you care about uninstallation, you'll need to parse the "PATH" variable to back it off when the user uninstalls.