:: 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'
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
5条答案
按热度按时间zd287kbt1#
使用SETX command(注意后缀“x”)设置在cmd窗口关闭后仍然存在的变量。
例如,要设置值为“bar”的env变量“foo”:
不过,如果打印使用情况(
setx /?
),则值得阅读显示的“注解”,特别是:1.在本地系统上,此工具创建或修改的变量将在以后的命令窗口中可用,但在当前的CMD.exe命令窗口中不可用。
1.在远程系统上,此工具创建或修改的变量将在下次登录会话时可用。
在PowerShell中,为[Environment]::SetEnvironmentVariable命令。
lokaqttq2#
MSDN documentation for environment variables告诉您要做什么:
若要以编程方式添加或修改系统环境变量,请将其添加到HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment注册表项,然后广播一条WM_SETTINGCHANGE消息,并将lParam设置为字符串“Environment”。这将允许应用程序(如shell)获取您的更新。
你当然需要管理员权限来做这件事。我知道没有办法从Windows批处理广播Windows消息,所以你需要写一个小程序来做这件事。
stszievb3#
gtlvzcf84#
事实上SET TEST_VARIABLE=value只对当前进程有效,所以
SETX
是必需的。这是一个在用户级别永久存储环境变量的快速示例。1.**在命令中,
SETX TEST_VARIABLE etc
。**尚未应用(echo %TEST_VARIABLE%
显示%TEST_VARIABLE%
,1.快速检查:打开命令,
echo %TEST_VARIABLE%
显示etc
。etc
。rfbsl7qr5#
VBScript(.vbs)的示例