简体   繁体   English

批处理脚本计算机环境变量

[英]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. 我有一个Windows批处理脚本,该脚本获取PATH环境变量,检查它是否具有某些值,然后将其重新设置。 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. 这可行,但是问题是我之前安装的其他东西创建了一个名为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. 当我在批处理脚本中访问%PATH%变量时,它会将用户环境变量PATH和计算机环境变量PATH串联在一起。 Everytime I run the script the user variable PATH gets appended to the machine environment variable. 每次运行脚本时,用户变量PATH都会附加到计算机环境变量中。 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. 虽然我可以简单地删除用户环境变量PATH,但这不是一个好的通用解决方案,因为我不能保证运行脚本的人员是否也会遇到同样的问题。

Note this seems to be specific to the PATH variable 请注意,这似乎特定于PATH变量

There is at least one other problem with your approach: it will expand any environment variables present in PATH, which may be undesirable. 您的方法还存在至少另一个问题:它将扩展PATH中存在的所有环境变量,这可能是不希望的。 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. 另外,您可能会发现setx偶尔挂起,我相信这是由于其他应用程序在广播更改时未按预期响应。

The best solution is probably to build an MSI file or use another well-developed installer technology. 最好的解决方案可能是生成MSI文件或使用另一种发达的安装程序技术。

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. 另请参阅有关SuperUser的问题 There's an answer there which includes a batch-file-based solution, although it doesn't work reliably. 有一个答案,其中包括基于批处理文件的解决方案,尽管它不能可靠地工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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