Search code examples
windowsbatch-fileenvironment-variablescommand-line-tool

How to reset environment variable set with setx in Windows


Initial state: ABC_HOME C:\abc\bin\

In the batch file the variable is changed:

setx ABC_HOME "%ABC_HOME%;E:\newAbc\abc\bin\"

How can I return to the state ABC_HOME C:\abc\bin\?


Solution

  • Since ABC_HOME is defined before the start of the batch file, we can simply set a temporary variable to store the old value:

    SET OLD_ABC_HOME=%ABC_HOME%
    setx ABC_HOME "%ABC_HOME%;E:\newAbc\abc\bin\"
    <your code here>
    setx ABC_HOME %OLD_ABC_HOME%
    

    If, however, you're using setx multiple times in the same batch file, you would have to query the registry to get the updated value, so you could use something like:

    setx ABC_HOME C:\abc\bin\
    FOR /F "tokens=2* delims= " %%a IN ('reg query HKCU\Environment /v ABC_HOME') DO SET OLD_ABC_HOME=%%b
    setx ABC_HOME "%ABC_HOME%;E:\newAbc\abc\bin\"
    <your code here>
    setx ABC_HOME %OLD_ABC_HOME%
    

    The reason for this is that setx doesn't apply to the environment of the cmd.exe instance that it's run in.

    Explanation

    • reg query HKCU\Environment /v ABC_HOME uses the Windows Registry to get the value of the ABC_HOME variable, since this is not available in your batch environment.
    • FOR /F "tokens=2* delims= " %%a IN ('...') DO will loop through the output of the reg query command and split it into three pieces.
      • delims= will set the space character as the delimiter for splitting the output
      • tokens=2* specifies which parts of the split output we want. The second piece will go into the %%a variable and the third portion and all portions after will go into the %%b variable. This way your variables can contain spaces.
      • SET OLD_ABC_HOME=%%b will set a temporary environment variable containing the contents of ABC_HOME.
    • setx ABC_HOME %OLD_ABC_HOME% will set ABC_HOME back to the old value it had before you ran your other code. It must be at the end of your code.

    Further reading