Search code examples
windowsbatch-fileenvironment-variablescmd

Set a persistent environment variable from cmd.exe


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?


Solution

  • 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 /m
    

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

    1. 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.

    2. 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.