PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 21, 2022

[FIXED] How to reset/remove the environment variables set using setx in windows?

 August 21, 2022     batch-file, command-line-tool, environment-variables, windows     No comments   

Issue

Initial state: ABC_HOME C:\abc\bin\

start of batch file setx ABC_HOME "%ABC_HOME%;E:\newAbc\abc\bin\"
....
after the appropriate execution
*What is the command* - run this command to get final state.

Final 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

  • Reg - SS64.com
  • Setx - SS64.com
  • Set - SS64.com
  • For (command) - SS64.com
  • Internal commands (like SET) - SS64.com


Answered By - Worthwelle
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing