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_HOMEuses the Windows Registry to get the value of theABC_HOMEvariable, since this is not available in your batch environment.FOR /F "tokens=2* delims= " %%a IN ('...') DOwill loop through the output of thereg querycommand and split it into three pieces.delims=will set the space characteras the delimiter for splitting the outputtokens=2*specifies which parts of the split output we want. The second piece will go into the%%avariable and the third portion and all portions after will go into the%%bvariable. This way your variables can contain spaces.SET OLD_ABC_HOME=%%bwill set a temporary environment variable containing the contents ofABC_HOME.
setx ABC_HOME %OLD_ABC_HOME%will setABC_HOMEback 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.