My requirement is to add one of the directory to path environment variable in windows at the time of installing my application and remove the same from path environment variable at the time of uninstallation using batch file.
In one of the stackoverflow answer related to this suggested the following to add a directory to path environment variable.
setx path C:\Program Files (x86)\MyApp\
It is adding to path variable but when I try to add one more, it overwrites the existing value which I have added. How to avoid this?
How to remove the directory path which I have added from path environment variable?
You should be able to use the existing value of it like this:
To remove it you could probably do something like this:
Which would substitute the path it was given with nothing to delete it.
You need to check if user's part of
path
variable is empty, e.g. for adding a directory as follows:Note that I use
reg add
instead ofsetx
command. See also this Rojo's answer for exhaustive explanation.Output.
Above output shows that the only check if a key is empty does not suffice as running it twice would add the same directory twice as well.
However, checking if a
path
key (user or machine-wide) contains a particular directory is not such simple task. For instance, some entries inpath
contain a trailing\
backslash while others don't. Moreover, some entries in apath
registry value ofREG_EXPAND_SZ
could be tangled in other environment variables e.g.%ProgramFiles%\SomeApp
instead ofC:\Program Files\SomeApp
etc.The following complex script could help to analyse Windows
path
environment variables (note that it could show incorrect values if a path contains an exclamation mark!
due to enabled delayed expansion):