我必须在不同的 Windows 计算机上设置环境变量,但我不想通过进入“我的电脑”的属性屏幕来手动更改它们,
我想使用批处理文件从命令行执行此操作。据我了解,使用 set 只会更改我将在命令窗口中调用的进程的变量。
我想明确地设置它,所以稍后,当运行新进程时,它将使用我设置的那些新设置。有没有办法从命令行做到这一点?
I have to set environment variables on different windows machines, but I don't want to be bothered changing them manually by getting on the properties screen of "My Computer"
I want to do it from the command line, with a batch file. As far as I understand, using set will only change the variable for the processes I will call in the command window.
I want to set it definitely, so later, when running a new process, it will use those new settings I have set. Is there a way to do that from the command line?
发布评论
评论(5)
使用 SETX 命令(注意“x ' 后缀)设置在 cmd 窗口关闭后仍然存在的变量。
例如,要设置值为“bar”的环境变量“foo”:
尽管打印用法(
setx /?
)时显示的“注释”值得阅读,特别是:在 PowerShell 中,[Environment]::SetEnvironmentVariable 命令。
Use the SETX command (note the 'x' suffix) to set variables that persist after the cmd window has been closed.
For example, to set an env var "foo" with value of "bar":
Though it's worth reading the 'notes' that are displayed if you print the usage (
setx /?
), in particular:In PowerShell, the [Environment]::SetEnvironmentVariable command.
环境变量的 MSDN 文档告诉您该怎么做:
您当然需要管理员权限才能执行此操作。我知道没有办法从 Windows 批处理中广播 Windows 消息,因此您需要编写一个小程序来执行此操作。
The MSDN documentation for environment variables tells you what to do:
You will of course need admin rights to do this. I know of no way to broadcast a windows message from Windows batch so you'll need to write a small program to do this.
事实上 SET TEST_VARIABLE=value 仅适用于当前进程,因此需要
SETX
。在用户级别永久存储环境变量的快速示例。SETX TEST_VARIABLE等
。尚未应用(echo %TEST_VARIABLE%
显示%TEST_VARIABLE%
,echo %TEST_VARIABLE%
显示etc
etc
的变量 TEST_VARIABLE。Indeed SET TEST_VARIABLE=value works for current process only, so
SETX
is required. A quick example for permanently storing an environment variable at user level.SETX TEST_VARIABLE etc
. Not applied yet (echo %TEST_VARIABLE%
shows%TEST_VARIABLE%
,echo %TEST_VARIABLE%
showsetc
.etc
.VBScript (.vbs) 的示例
An example with VBScript (.vbs)