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

    Further reading