是否有从 Windows 中的命令提示符刷新环境变量的命令?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/171588/
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
Is there a command to refresh environment variables from the command prompt in Windows?
提问by Eric Schoonover
If I modify or add an environment variable I have to restart the command prompt. Is there a command I could execute that would do this without restarting CMD?
如果我修改或添加环境变量,我必须重新启动命令提示符。是否有我可以执行的命令可以在不重新启动 CMD 的情况下执行此操作?
采纳答案by itsadok
You can capture the system environment variables with a vbs script, but you need a bat script to actually change the current environment variables, so this is a combined solution.
可以用vbs脚本捕获系统环境变量,但是实际改变当前环境变量需要bat脚本,所以这是一个组合方案。
Create a file named resetvars.vbs
containing this code, and save it on the path:
创建一个名为resetvars.vbs
包含此代码的文件,并将其保存在路径中:
Set oShell = WScript.CreateObject("WScript.Shell")
filename = oShell.ExpandEnvironmentStrings("%TEMP%\resetvars.bat")
Set objFileSystem = CreateObject("Scripting.fileSystemObject")
Set oFile = objFileSystem.CreateTextFile(filename, TRUE)
set oEnv=oShell.Environment("System")
for each sitem in oEnv
oFile.WriteLine("SET " & sitem)
next
path = oEnv("PATH")
set oEnv=oShell.Environment("User")
for each sitem in oEnv
oFile.WriteLine("SET " & sitem)
next
path = path & ";" & oEnv("PATH")
oFile.WriteLine("SET PATH=" & path)
oFile.Close
create another file name resetvars.bat containing this code, same location:
创建另一个包含此代码的文件名 resetvars.bat,位置相同:
@echo off
%~dp0resetvars.vbs
call "%TEMP%\resetvars.bat"
When you want to refresh the environment variables, just run resetvars.bat
当你想刷新环境变量时,只需运行 resetvars.bat
Apologetics:
道歉:
The two main problems I had coming up with this solution were
我提出这个解决方案的两个主要问题是
a.I couldn't find a straightforward way to export environment variables from a vbs script back to the command prompt, and
一种。我找不到将环境变量从 vbs 脚本导出回命令提示符的直接方法,并且
b.the PATH environment variable is a concatenation of the user and the system PATH variables.
湾 PATH 环境变量是用户和系统 PATH 变量的串联。
I'm not sure what the general rule is for conflicting variables between user and system, so I elected to make user override system, except in the PATH variable which is handled specifically.
我不确定用户和系统之间的冲突变量的一般规则是什么,所以我选择让用户覆盖系统,除了专门处理的 PATH 变量。
I use the weird vbs+bat+temporary bat mechanism to work around the problem of exporting variables from vbs.
我使用奇怪的 vbs+bat+temporary bat 机制来解决从 vbs 导出变量的问题。
Note: this script does not delete variables.
注意:此脚本不会删除变量。
This can probably be improved.
这可能可以改进。
ADDED
添加
If you need to export the environment from one cmd window to another, use this script (let's call it exportvars.vbs
):
如果您需要将环境从一个 cmd 窗口导出到另一个,请使用此脚本(我们称之为exportvars.vbs
):
Set oShell = WScript.CreateObject("WScript.Shell")
filename = oShell.ExpandEnvironmentStrings("%TEMP%\resetvars.bat")
Set objFileSystem = CreateObject("Scripting.fileSystemObject")
Set oFile = objFileSystem.CreateTextFile(filename, TRUE)
set oEnv=oShell.Environment("Process")
for each sitem in oEnv
oFile.WriteLine("SET " & sitem)
next
oFile.Close
Run exportvars.vbs
in the window you want to export from, then switch to the window you want to export to, and type:
运行exportvars.vbs
中要导出的窗口从,然后切换到要出口的窗口来,并键入:
"%TEMP%\resetvars.bat"
回答by anonymous coward
Here is what Chocolatey uses.
这是 Chocolatey 使用的内容。
https://github.com/chocolatey/choco/blob/master/src/chocolatey.resources/redirects/RefreshEnv.cmd
https://github.com/chocolatey/choco/blob/master/src/chocolatey.resources/redirects/RefreshEnv.cmd
@echo off
::
:: RefreshEnv.cmd
::
:: Batch file to read environment variables from registry and
:: set session variables to these values.
::
:: With this batch file, there should be no need to reload command
:: environment every time you want environment changes to propagate
echo | set /p dummy="Reading environment variables from registry. Please wait... "
goto main
:: Set one environment variable from registry key
:SetFromReg
"%WinDir%\System32\Reg" QUERY "%~1" /v "%~2" > "%TEMP%\_envset.tmp" 2>NUL
for /f "usebackq skip=2 tokens=2,*" %%A IN ("%TEMP%\_envset.tmp") do (
echo/set %~3=%%B
)
goto :EOF
:: Get a list of environment variables from registry
:GetRegEnv
"%WinDir%\System32\Reg" QUERY "%~1" > "%TEMP%\_envget.tmp"
for /f "usebackq skip=2" %%A IN ("%TEMP%\_envget.tmp") do (
if /I not "%%~A"=="Path" (
call :SetFromReg "%~1" "%%~A" "%%~A"
)
)
goto :EOF
:main
echo/@echo off >"%TEMP%\_env.cmd"
:: Slowly generating final file
call :GetRegEnv "HKLM\System\CurrentControlSet\Control\Session Manager\Environment" >> "%TEMP%\_env.cmd"
call :GetRegEnv "HKCU\Environment">>"%TEMP%\_env.cmd" >> "%TEMP%\_env.cmd"
:: Special handling for PATH - mix both User and System
call :SetFromReg "HKLM\System\CurrentControlSet\Control\Session Manager\Environment" Path Path_HKLM >> "%TEMP%\_env.cmd"
call :SetFromReg "HKCU\Environment" Path Path_HKCU >> "%TEMP%\_env.cmd"
:: Caution: do not insert space-chars before >> redirection sign
echo/set Path=%%Path_HKLM%%;%%Path_HKCU%% >> "%TEMP%\_env.cmd"
:: Cleanup
del /f /q "%TEMP%\_envset.tmp" 2>nul
del /f /q "%TEMP%\_envget.tmp" 2>nul
:: Set these variables
call "%TEMP%\_env.cmd"
echo | set /p dummy="Done"
echo .
回答by jolly
On Windows 7/8/10, you can install Chocolatey, which has a script for this built-in.
在 Windows 7/8/10 上,您可以安装 Chocolatey,它有一个内置脚本。
After installing Chocolatey, just type refreshenv
.
安装 Chocolatey 后,只需输入refreshenv
.
回答by Kev
By design there isn't a built inmechanism for Windows to propagate an environment variable add/change/remove to an already running cmd.exe, either from another cmd.exe or from "My Computer -> Properties ->Advanced Settings -> Environment Variables".
根据设计,Windows没有内置机制将环境变量添加/更改/删除传播到已运行的 cmd.exe,无论是从另一个 cmd.exe 还是从“我的电脑 -> 属性 -> 高级设置 ->环境变量”。
If you modify or add a new environment variable outside of the scope of an existing open command prompt you either need to restart the command prompt, or, manually add using SET in the existing command prompt.
如果在现有打开的命令提示符范围之外修改或添加新的环境变量,则需要重新启动命令提示符,或者在现有命令提示符中使用 SET 手动添加。
The latest accepted answershows a partial work-around by manually refreshing allthe environment variables in a script. The script handles the use case of changing environment variables globally in "My Computer...Environment Variables", but if an environment variable is changed in one cmd.exe the script will not propagate it to another running cmd.exe.
在最新接受的答案显示了部分工作由各地手动刷新所有的环境变量的脚本。该脚本处理在“我的电脑...环境变量”中全局更改环境变量的用例,但如果在一个 cmd.exe 中更改环境变量,脚本将不会将其传播到另一个正在运行的 cmd.exe。
回答by wharding28
I came across this answer before eventually finding an easier solution.
在最终找到更简单的解决方案之前,我遇到了这个答案。
Simply restart explorer.exe
in Task Manager.
只需explorer.exe
在任务管理器中重新启动。
I didn't test, but you may also need to reopen you command prompt.
我没有测试,但您可能还需要重新打开命令提示符。
Credit to Timo Huovinenhere: Node not recognized although successfully installed(if this helped you, please go give this man's comment credit).
感谢蒂莫Huovinen这里:节点无法识别,虽然安装成功(如果这帮助了你,请去给这人的评论信用)。
回答by kristofer m?nsson
This works on windows 7: SET PATH=%PATH%;C:\CmdShortcuts
这适用于 Windows 7: SET PATH=%PATH%;C:\CmdShortcuts
tested by typing echo %PATH% and it worked, fine. also set if you open a new cmd, no need for those pesky reboots any more :)
通过输入 echo %PATH% 进行测试,它工作正常。如果你打开一个新的 cmd,也可以设置,不再需要那些讨厌的重启:)
回答by Jens A. Koch
Use "setx" and restart cmd prompt
使用“setx”并重新启动cmd提示符
There is a command line tool named "setx" for this job. It's for reading and writingenv variables. The variables persist after the command window has been closed.
此作业有一个名为“ setx”的命令行工具。它用于读取和写入env 变量。命令窗口关闭后变量仍然存在。
It "Creates or modifies environment variables in the user or system environment, without requiring programming or scripting. The setxcommand also retrieves the values of registry keys and writes them to text files."
它“在用户或系统环境中创建或修改环境变量,无需编程或脚本编写。setx命令还检索注册表项的值并将它们写入文本文件。”
Note: variables created or modified by this tool will be available in future command windows but not in the current CMD.exe command window. So, you have to restart.
注意:此工具创建或修改的变量将在未来的命令窗口中可用,但在当前的 CMD.exe 命令窗口中不可用。所以,你必须重新启动。
If setx
is missing:
如果setx
缺少:
Or modify the registry
或者修改注册表
MSDNsays:
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 lParamset 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)获取您的更新。
回答by Brian Weed
Calling this function has worked for me:
调用这个函数对我有用:
VOID Win32ForceSettingsChange()
{
DWORD dwReturnValue;
::SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM) "Environment", SMTO_ABORTIFHUNG, 5000, &dwReturnValue);
}
回答by Christopher Holmes
The best method I came up with was to just do a Registry query. Here is my example.
我想出的最好方法是只进行注册表查询。这是我的例子。
In my example I did an install using a Batch file that added new environment variables. I needed to do things with this as soon as the install was complete, but was unable to spawn a new process with those new variables. I tested spawning another explorer window and called back to cmd.exe and this worked but on Vista and Windows 7, Explorer only runs as a single instance and normally as the person logged in. This would fail with automation since I need my admin creds to do things regardless of running from local system or as an administrator on the box. The limitation to this is that it does not handle things like path, this only worked on simple enviroment variables. This allowed me to use a batch to get over to a directory (with spaces) and copy in files run .exes and etc. This was written today from may resources on stackoverflow.com
在我的示例中,我使用添加新环境变量的批处理文件进行了安装。我需要在安装完成后立即执行此操作,但无法使用这些新变量生成新进程。我测试了生成另一个资源管理器窗口并回调 cmd.exe 并且这有效,但是在 Vista 和 Windows 7 上,资源管理器仅作为单个实例运行,并且通常作为登录的人运行。这将因自动化而失败,因为我需要我的管理员凭据无论是从本地系统运行还是以管理员身份运行,都可以做一些事情。对此的限制是它不处理路径之类的事情,这只适用于简单的环境变量。这使我可以使用批处理转到目录(带空格)并复制运行 .exes 等文件。这是今天从 stackoverflow.com 上的 May 资源编写的
Orginal Batch calls to new Batch:
原始批次调用新批次:
testenvget.cmd SDROOT (or whatever the variable)
testenvget.cmd SDROOT(或任何变量)
@ECHO OFF
setlocal ENABLEEXTENSIONS
set keyname=HKLM\System\CurrentControlSet\Control\Session Manager\Environment
set value=%1
SET ERRKEY=0
REG QUERY "%KEYNAME%" /v "%VALUE%" 2>NUL| FIND /I "%VALUE%"
IF %ERRORLEVEL% EQU 0 (
ECHO The Registry Key Exists
) ELSE (
SET ERRKEY=1
Echo The Registry Key Does not Exist
)
Echo %ERRKEY%
IF %ERRKEY% EQU 1 GOTO :ERROR
FOR /F "tokens=1-7" %%A IN ('REG QUERY "%KEYNAME%" /v "%VALUE%" 2^>NUL^| FIND /I "%VALUE%"') DO (
ECHO %%A
ECHO %%B
ECHO %%C
ECHO %%D
ECHO %%E
ECHO %%F
ECHO %%G
SET ValueName=%%A
SET ValueType=%%B
SET C1=%%C
SET C2=%%D
SET C3=%%E
SET C4=%%F
SET C5=%%G
)
SET VALUE1=%C1% %C2% %C3% %C4% %C5%
echo The Value of %VALUE% is %C1% %C2% %C3% %C4% %C5%
cd /d "%VALUE1%"
pause
REM **RUN Extra Commands here**
GOTO :EOF
:ERROR
Echo The the Enviroment Variable does not exist.
pause
GOTO :EOF
Also there is another method that I came up with from various different ideas. Please see below. This basically will get the newest path variable from the registry however, this will cause a number of issues beacuse the registry query is going to give variables in itself, that means everywhere there is a variable this will not work, so to combat this issue I basically double up the path. Very nasty. The more perfered method would be to do: Set Path=%Path%;C:\Program Files\Software....\
还有另一种方法是我从各种不同的想法中想到的。请参阅下文。这基本上将从注册表中获取最新的路径变量,但是,这将导致许多问题,因为注册表查询本身会给出变量,这意味着到处都有变量这将不起作用,因此为了解决这个问题,我基本上把路径加倍。很恶心。更可取的方法是: Set Path=%Path%;C:\Program Files\Software....\
Regardless here is the new batch file, please use caution.
不管这里是新的批处理文件,请谨慎使用。
@ECHO OFF
SETLOCAL ENABLEEXTENSIONS
set org=%PATH%
for /f "tokens=2*" %%A in ('REG QUERY "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path ^|FIND /I "Path"') DO (
SET path=%%B
)
SET PATH=%org%;%PATH%
set path
回答by Richard Woodruff
The easiest way to add a variable to the path without rebooting for the current session is to open the command prompt and type:
将变量添加到路径而不为当前会话重新启动的最简单方法是打开命令提示符并键入:
PATH=(VARIABLE);%path%
and press enter.
并按enter。
to check if your variable loaded, type
要检查您的变量是否已加载,请键入
PATH
and press enter. However, the variable will only be a part of the path until you reboot.
并按enter。但是,在您重新启动之前,该变量将只是路径的一部分。