简体   繁体   中英

batch script machine environment variables

I have a windows batch script that gets the PATH environment variable, checks if it has some value in it, and then sets it back. For example:

SET CURRPATH=%PATH%
:: do some stuff to check for a value in CURRPATH and add the value in if it is not in there
setx PATH %PATH%

This works, but the problem is that something else I installed previously created a user system environment variable named PATH. When I access the %PATH% variable in my batch script, it concatenates both the user environment variable PATH and the machine environment variable PATH. Everytime I run the script the user variable PATH gets appended to the machine environment variable. Is there a way to just access the machine environment variable?

While I could simply remove the user environment variable PATH, this is not a good general solution since I cannot guarantee if the people running the script will have this same issue.

Note this seems to be specific to the PATH variable

There is at least one other problem with your approach: it will expand any environment variables present in PATH, which may be undesirable. Also you may find that setx occasionally hangs, I believe this is due to other applications not responding as expected when it broadcasts the change.

The best solution is probably to build an MSI file or use another well-developed installer technology.

Second best would be to write an application (a real application, not a batch script) to manipulate the registry setting holding the environment variable. The registry key containing the machine environment variables can be found here:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

See also this question on SuperUser. There's an answer there which includes a batch-file-based solution, although it doesn't work reliably.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM