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 theABC_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 thereg query
command and split it into three pieces.delims=
will set the space charactertokens=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 ofABC_HOME
.
setx ABC_HOME %OLD_ABC_HOME%
will setABC_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)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.