Set a persistent environment variable from cmd.exe

0x26res picture 0x26res · May 5, 2011 · Viewed 138.7k times · Source

I have to set environment variables on different windows machines, but I don't want to be bothered changing them manually by getting on the properties screen of "My Computer"

I want to do it from the command line, with a batch file. As far as I understand, using set will only change the variable for the processes I will call in the command window.

I want to set it definitely, so later, when running a new process, it will use those new settings I have set. Is there a way to do that from the command line ?

Answer

Vik David picture Vik David · May 5, 2011

Use the SETX command (note the 'x' suffix) to set variables that persist after the cmd window has been closed.

For example, to set an env var "foo" with value of "bar":

setx foo bar

Though it's worth reading the 'notes' that are displayed if you print the usage (setx /?), in particular:

2) On a local system, variables created or modified by this tool will be available in future command windows but not in the current CMD.exe command window.

3) On a remote system, variables created or modified by this tool will be available at the next logon session.

In PowerShell, the [Environment]::SetEnvironmentVariable command.