Wednesday, June 29, 2016

SETX: Permanently setting a Windows System Environment Variable from the Command-Line

For two decades I have used SET from the Windows from the command-line to display environment variables and to temporarily assign environment variables meaning the environment variables are local. The environment variables create exist for the duration of the console window in which SET was used to assign the environment variable.

On a recent project, I was required to permanently assign an environment variable from command-line (part of a build automation process that was invoked via batch files). After a quick search I found SETX which unbeknownst to me was including in Windows NT 4.0 Resource kit (circa 1996). SETX is akin to SETENV on Linux/Unix.

The features of SETX are extensive and are well documented at Setx. By default the environment variables created by SETX are local just as are the environment variables created by SET. The /m command-line option causes SETX to create environment variables that are persisted as system environment variables.

The standard command-line that allows SETX to create system environment variables is as follows:
  SETX <Environmental Variable Name> <Value> /m

An example of SETX is action is as follows:


Above a system environment variable is created named SomeKeyEnvVariable and is assigned a value of C:\foo\bar. The /m is the option specifies a system environment variable is created. Notice in the head of the previous screen shot that that command prompt is being run with administrator privileges. If SETX is executed without administrator privileges then SETX will fail.

Before discovering SETX, I was obligated to use the dialogs provided with Windows in order to create system environment variables. To demonstrate let's varify the previous SETX command actually created SomeKeyEnvVariable:

To check the state of environment variables navigate as follows:
    Control Panel > System and Security > 
        System > Advanced system settings

The sequence of screens to read environment variables is as follows. First open Control Panel:


Select the folder System and Security from Control Panel:


From System and Security select System:


On the left side click on Advanced system settings:


Click on the Environment Variables button to see the environment variables:


Notice in the Environment Variables dialog above, the SomeKeyEnvVariable system environment variable was created courtesy of SETX running with administrative privileges.

No comments :

Post a Comment