windows 从 cmd.exe 设置持久环境变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5898131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 08:21:15  来源:igfitidea点击:

Set a persistent environment variable from cmd.exe

windowsbatch-fileenvironment-variablescmd

提问by Arthur

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"

我必须在不同的 Windows 机器上设置环境变量,但我不想通过进入“我的电脑”的属性屏幕来手动更改它们

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.

我想使用批处理文件从命令行执行此操作。据我了解,使用 set 只会更改我将在命令窗口中调用的进程的变量。

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 ?

我想确定地设置它,所以稍后,当运行一个新进程时,它将使用我设置的那些新设置。有没有办法从命令行做到这一点?

回答by Vik David

Use the SETX command(note the 'x' suffix) to set variables that persist after the cmd window has been closed.

使用SETX 命令(注意“x”后缀)设置在 cmd 窗口关闭后仍然存在的变量。

For example, to set an env var "foo" with value of "bar":

例如,要设置一个值为“bar”的环境变量“foo”:

setx foo bar

Though it's worth reading the 'notes' that are displayed if you print the usage (setx /?), in particular:

尽管打印用法 ( setx /?) 时显示的“注释”值得一读,特别是:

2) On a local system, variables created or modified by this tool will be available in future command windows but not in the current CMD.exe command window.

3) On a remote system, variables created or modified by this tool will be available at the next logon session.

2) 在本地系统上,此工具创建或修改的变量将在未来的命令窗口中可用,但在当前的 CMD.exe 命令窗口中不可用。

3) 在远程系统上,此工具创建或修改的变量将在下一次登录会话中可用。

In PowerShell, the [Environment]::SetEnvironmentVariablecommand.

在 PowerShell 中,[Environment]::SetEnvironmentVariable命令。

回答by David Heffernan

The MSDN documentation for environment variablestells you what to do:

环境变量MSDN 文档告诉您该怎么做:

To programmatically add or modify system environment variables, add them to the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environmentregistry key, then broadcast a WM_SETTINGCHANGEmessage with lParam set to the string "Environment". This allows applications, such as the shell, to pick up your updates.

要以编程方式添加或修改系统环境变量,请将它们添加到HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment注册表项,然后广播一条WM_SETTINGCHANGE消息,其中 lParam 设置为字符串“Environment”。这允许应用程序(例如 shell)获取您的更新。

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.

您当然需要管理员权限才能执行此操作。我知道无法从 Windows 批处理中广播 Windows 消息,因此您需要编写一个小程序来执行此操作。

回答by Justin Peal

' SetVar.vbs
Sub sety(wsh, action, typey, vary, value)
  Dim wu
  Set wu = wsh.Environment(typey)
  wui = wu.Item(vary)
  Select Case action
    Case "ls"
      WScript.Echo wui
    Case "del"
      On Error Resume Next
      wu.remove(vary)
      On Error Goto 0
    Case "set"
      wu.Item(vary) = value
    Case "add"
      If wui = "" Then
        wu.Item(vary) = value
      ElseIf InStr(UCase(";" & wui & ";"), UCase(";" & value & ";")) = 0 Then
        wu.Item(vary) = value & ";" & wui
      End If
    Case Else
      WScript.Echo "Bad action"
  End Select
End Sub

Dim wsh, args
Set wsh = WScript.CreateObject("WScript.Shell")
Set args = WScript.Arguments
Select Case WScript.Arguments.Length
  Case 3
    value = ""
  Case 4
    value = args(3)
  Case Else
    WScript.Echo "Arguments - 0: ls,del,set,add; 1: user,system, 2: variable; 3: value"
    value = "```"
End Select
If Not value = "```" Then
  ' 0: ls,del,set,add; 1: user,system, 2: variable; 3: value
  sety wsh, args(0), args(1), UCase(args(2)), value
End If

回答by Alexei

Indeed SET TEST_VARIABLE=value works for current process only, so SETXis required. A quick example for permanently storing an environment variable at user level.

实际上 SET TEST_VARIABLE=value 仅适用于当前进程,因此SETX是必需的。在用户级别永久存储环境变量的快速示例。

  1. In cmd, SETX TEST_VARIABLE etc.Not applied yet (echo %TEST_VARIABLE%shows %TEST_VARIABLE%,
  2. Quick check: open cmd, echo %TEST_VARIABLE%shows etc.
  3. GUI check: System Properties -> Advanced -> Environment variables -> User variables for -> you should see Varible TEST_VARIABLE with value etc.
  1. 在 cmd 中,SETX TEST_VARIABLE etc. 尚未申请(echo %TEST_VARIABLE%显示%TEST_VARIABLE%
  2. 快速检查:打开cmd,echo %TEST_VARIABLE%显示etc.
  3. GUI 检查: System Properties -> Advanced -> Environment variables -> User variables for -> 你应该看到 Varible TEST_VARIABLE with value etc

回答by gseattle

:: Sets environment variables for both the current `cmd` window 
::   and/or other applications going forward.
:: I call this file keyz.cmd to be able to just type `keyz` at the prompt 
::   after changes because the word `keys` is already taken in Windows.

@echo off

:: set for the current window
set APCA_API_KEY_ID=key_id
set APCA_API_SECRET_KEY=secret_key
set APCA_API_BASE_URL=https://paper-api.alpaca.markets

:: setx also for other windows and processes going forward
setx APCA_API_KEY_ID     %APCA_API_KEY_ID%
setx APCA_API_SECRET_KEY %APCA_API_SECRET_KEY%
setx APCA_API_BASE_URL   %APCA_API_BASE_URL%

:: Displaying what was just set.
set apca

:: Or for copy/paste manually ...
:: setx APCA_API_KEY_ID     'key_id'
:: setx APCA_API_SECRET_KEY 'secret_key'
:: setx APCA_API_BASE_URL   'https://paper-api.alpaca.markets'