I’ve made some changes to the %PATH%
variable in the registry. Now, I’d like to see those changes applied without having to go so far as a logoff, reboot, or reload of Explorer. Is there a way this can be done?
I’d rather do this via some sort of command that can be put at the end of a .BAT
file, and don’t want to use any tools other than those that come with the OS in a fresh install. This needs to be minimally compatible with Windows XP SP3, and should work all the way up to Windows 7 x64 and Server 2008 R2.
asked Feb 16, 2012 at 21:36
5
- Change either User or System PATH in System Properties.
- Running this batch file pulls the new PATH variables with a REG query.
- The FOR commands parse the PATH variables from the REG results.
- The current PATH is updated to the registry values.
- I use ConEmu for my consoles and it runs this batch file on each new console to refresh the PATH so a reboot isn’t necessary.
@echo off
echo.
echo Refreshing PATH from registry
:: Get System PATH
for /f "tokens=2*" %%A in ('reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path') do set syspath=%%B
:: Get User Path
for /f "tokens=2*" %%A in ('reg query "HKCU\Environment" /v Path') do set userpath=%%B
:: Set Refreshed Path
set PATH=%userpath%;%syspath%
echo Refreshed PATH
echo %PATH%
«`
The task Commands parameter in ConEmu launches C:\Windows\System32\cmd.exe with the /k switch to run the refreshpath.cmd above and then remain. That updates the path and leaves the console open.
C:\Windows\System32\cmd.exe /k refreshpath.cmd
answered Dec 25, 2015 at 15:57
DaveDave
811 silver badge5 bronze badges
3
If you are trying to use the new value of the path variable from within a Windows command shell, all you should need to do is close your command shell window and open a new one. The new command shell will load the updated path variable.
So I think the answer to your original question sort of depends on where exactly you are trying to see the change take effect… Is there something specific that is not working for you?
answered Feb 16, 2012 at 22:29
Shannon WagnerShannon Wagner
1,0411 gold badge10 silver badges20 bronze badges
6
The easiest way to add a variable to the path without rebooting is to open the command prompt and type: PATH=(VARIABLE);%path% and press enter. To check if your variable loaded, type PATH and press enter.
answered Jun 28, 2016 at 22:25
1
- Change the PATH variable from the UI in environment variables.
- Add a new environment variable, call it something random. Maybe something like CHANGE_TO_UPDATE and put a random value like x in it.
- Remember to restart cmd.exe or whatever program that needs to see the new path variable.
This will actually trigger the settings to update when you launch a new application.
answered Mar 26, 2015 at 3:17
iopqiopq
993 bronze badges
You must log in to answer this question.
Not the answer you’re looking for? Browse other questions tagged
.
Not the answer you’re looking for? Browse other questions tagged
.
I’ve made some changes to the %PATH%
variable in the registry. Now, I’d like to see those changes applied without having to go so far as a logoff, reboot, or reload of Explorer. Is there a way this can be done?
I’d rather do this via some sort of command that can be put at the end of a .BAT
file, and don’t want to use any tools other than those that come with the OS in a fresh install. This needs to be minimally compatible with Windows XP SP3, and should work all the way up to Windows 7 x64 and Server 2008 R2.
asked Feb 16, 2012 at 21:36
5
- Change either User or System PATH in System Properties.
- Running this batch file pulls the new PATH variables with a REG query.
- The FOR commands parse the PATH variables from the REG results.
- The current PATH is updated to the registry values.
- I use ConEmu for my consoles and it runs this batch file on each new console to refresh the PATH so a reboot isn’t necessary.
@echo off
echo.
echo Refreshing PATH from registry
:: Get System PATH
for /f "tokens=2*" %%A in ('reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path') do set syspath=%%B
:: Get User Path
for /f "tokens=2*" %%A in ('reg query "HKCU\Environment" /v Path') do set userpath=%%B
:: Set Refreshed Path
set PATH=%userpath%;%syspath%
echo Refreshed PATH
echo %PATH%
«`
The task Commands parameter in ConEmu launches C:\Windows\System32\cmd.exe with the /k switch to run the refreshpath.cmd above and then remain. That updates the path and leaves the console open.
C:\Windows\System32\cmd.exe /k refreshpath.cmd
answered Dec 25, 2015 at 15:57
DaveDave
811 silver badge5 bronze badges
3
If you are trying to use the new value of the path variable from within a Windows command shell, all you should need to do is close your command shell window and open a new one. The new command shell will load the updated path variable.
So I think the answer to your original question sort of depends on where exactly you are trying to see the change take effect… Is there something specific that is not working for you?
answered Feb 16, 2012 at 22:29
Shannon WagnerShannon Wagner
1,0411 gold badge10 silver badges20 bronze badges
6
The easiest way to add a variable to the path without rebooting is to open the command prompt and type: PATH=(VARIABLE);%path% and press enter. To check if your variable loaded, type PATH and press enter.
answered Jun 28, 2016 at 22:25
1
- Change the PATH variable from the UI in environment variables.
- Add a new environment variable, call it something random. Maybe something like CHANGE_TO_UPDATE and put a random value like x in it.
- Remember to restart cmd.exe or whatever program that needs to see the new path variable.
This will actually trigger the settings to update when you launch a new application.
answered Mar 26, 2015 at 3:17
iopqiopq
993 bronze badges
You must log in to answer this question.
Not the answer you’re looking for? Browse other questions tagged
.
Not the answer you’re looking for? Browse other questions tagged
.
I made a better alternative to the Chocolatey refreshenv for cmd and cygwin which solves a lot of problems like:
-
The Chocolatey refreshenv is so bad if the variable have some
cmd meta-characters, see this test:add this to the path in HKCU\Environment:
test & echo baaaaaaaaaad
,
and run the chocolateyrefreshenv
you will see that it prints
baaaaaaaaaad
which is very bad, and the new path is not added to
your path variable.This script solve this and you can test it with any meta-character, even something so bad like:
; & % ' ( ) ~ + @ # $ { } [ ] , ` ! ^ | > < \ / " : ? * = . - _ & echo baaaad
-
refreshenv adds only system and user
environment variables, but CMD adds volatile variables too
(HKCU\Volatile Environment). This script will merge all the three and
remove any duplicates. -
refreshenv reset your PATH. This script append the new path to the
old path of the parent script which called this script. It is better
than overwriting the old path, otherwise it will delete any newly
added path by the parent script. -
This script solve this problem described in a comment here by @Gene
Mayevsky: refreshenv modifies env variables TEMP and TMP replacing
them with values stored in HKCU\Environment. In my case I run the
script to update env variables modified by Jenkins job on a slave
that’s running under SYSTEM account, so TEMP and TMP get substituted
by %USERPROFILE%\AppData\Local\Temp instead of C:\Windows\Temp. This
breaks build because linker cannot open system profile’s Temp folder.
I made one script for cmd and another for cygwin/bash,
you can found them here: https://github.com/badrelmers/RefrEnv
For cmd
This script uses vbscript so it works in all windows versions xp+
to use it save it as refrenv.bat and call it with call refrenv.bat
<!-- : Begin batch script
@echo off
REM PUSHD "%~dp0"
REM author: Badr Elmers 2021
REM description: refrenv = refresh environment. this is a better alternative to the chocolatey refreshenv for cmd
REM https://github.com/badrelmers/RefrEnv
REM https://stackoverflow.com/questions/171588/is-there-a-command-to-refresh-environment-variables-from-the-command-prompt-in-w
REM ___USAGE_____________________________________________________________
REM usage:
REM call refrenv.bat full refresh. refresh all non critical variables*, and refresh the PATH
REM debug:
REM to debug what this script do create this variable in your parent script like that
REM set debugme=yes
REM then the folder containing the files used to set the variables will be open. Then see
REM _NewEnv.cmd this is the file which run inside your script to setup the new variables, you
REM can also revise the intermediate files _NewEnv.cmd_temp_.cmd and _NewEnv.cmd_temp2_.cmd
REM (those two contains all the variables before removing the duplicates and the unwanted variables)
REM you can also put this script in windows\systems32 or another place in your %PATH% then call it from an interactive console by writing refrenv
REM *critical variables: are variables which belong to cmd/windows and should not be refreshed normally like:
REM - windows vars:
REM ALLUSERSPROFILE APPDATA CommonProgramFiles CommonProgramFiles(x86) CommonProgramW6432 COMPUTERNAME ComSpec HOMEDRIVE HOMEPATH LOCALAPPDATA LOGONSERVER NUMBER_OF_PROCESSORS OS PATHEXT PROCESSOR_ARCHITECTURE PROCESSOR_ARCHITEW6432 PROCESSOR_IDENTIFIER PROCESSOR_LEVEL PROCESSOR_REVISION ProgramData ProgramFiles ProgramFiles(x86) ProgramW6432 PUBLIC SystemDrive SystemRoot TEMP TMP USERDOMAIN USERDOMAIN_ROAMINGPROFILE USERNAME USERPROFILE windir SESSIONNAME
REM ___INFO_____________________________________________________________
REM :: this script reload environment variables inside cmd every time you want environment changes to propagate, so you do not need to restart cmd after setting a new variable with setx or when installing new apps which add new variables ...etc
REM This is a better alternative to the chocolatey refreshenv for cmd, which solves a lot of problems like:
REM The Chocolatey refreshenv is so bad if the variable have some cmd meta-characters, see this test:
REM add this to the path in HKCU\Environment: test & echo baaaaaaaaaad, and run the chocolatey refreshenv you will see that it prints baaaaaaaaaad which is very bad, and the new path is not added to your path variable.
REM This script solve this and you can test it with any meta-character, even something so bad like:
REM ; & % ' ( ) ~ + @ # $ { } [ ] , ` ! ^ | > < \ / " : ? * = . - _ & echo baaaad
REM refreshenv adds only system and user environment variables, but CMD adds volatile variables too (HKCU\Volatile Environment). This script will merge all the three and remove any duplicates.
REM refreshenv reset your PATH. This script append the new path to the old path of the parent script which called this script. It is better than overwriting the old path, otherwise it will delete any newly added path by the parent script.
REM This script solve this problem described in a comment by @Gene Mayevsky: refreshenv modifies env variables TEMP and TMP replacing them with values stored in HKCU\Environment. In my case I run the script to update env variables modified by Jenkins job on a slave that's running under SYSTEM account, so TEMP and TMP get substituted by %USERPROFILE%\AppData\Local\Temp instead of C:\Windows\Temp. This breaks build because linker cannot open system profile's Temp folder.
REM ________
REM this script solve things like that too:
REM The confusing thing might be that there are a few places to start the cmd from. In my case I run cmd from windows explorer and the environment variables did not change while when starting cmd from the "run" (windows key + r) the environment variables were changed.
REM In my case I just had to kill the windows explorer process from the task manager and then restart it again from the task manager.
REM Once I did this I had access to the new environment variable from a cmd that was spawned from windows explorer.
REM my conclusion:
REM if I add a new variable with setx, i can access it in cmd only if i run cmd as admin, without admin right i have to restart explorer to see that new variable. but running this script inside my script (who sets the variable with setx) solve this problem and i do not have to restart explorer
REM ________
REM windows recreate the path using three places at less:
REM the User namespace: HKCU\Environment
REM the System namespace: HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
REM the Session namespace: HKCU\Volatile Environment
REM but the original chocolatey script did not add the volatile path. This script will merge all the three and remove any duplicates. this is what windows do by default too
REM there is this too which cmd seems to read when first running, but it contains only TEMP and TMP,so i will not use it
REM HKEY_USERS\.DEFAULT\Environment
REM ___TESTING_____________________________________________________________
REM to test this script with extreme cases do
REM :: Set a bad variable
REM add a var in reg HKCU\Environment as the following, and see that echo is not executed. if you use refreshenv of chocolatey you will see that echo is executed which is so bad!
REM so save this in reg:
REM all 32 characters: & % ' ( ) ~ + @ # $ { } [ ] ; , ` ! ^ | > < \ / " : ? * = . - _ & echo baaaad
REM and this:
REM (^.*)(Form Product=")([^"]*") FormType="[^"]*" FormID="([0-9][0-9]*)".*$
REM and use set to print those variables and see if they are saved without change ; refreshenv fail dramatically with those variables
REM invalid characters (illegal characters in file names) in Windows using NTFS
REM \ / : * ? " < > | and ^ in FAT
REM __________________________________________________________________________________________
REM __________________________________________________________________________________________
REM __________________________________________________________________________________________
REM this is a hybrid script which call vbs from cmd directly
REM :: The only restriction is the batch code cannot contain - - > (without space between - - > of course)
REM :: The only restriction is the VBS code cannot contain </script>.
REM :: The only risk is the undocumented use of "%~f0?.wsf" as the script to load. Somehow the parser properly finds and loads the running .BAT script "%~f0", and the ?.wsf suffix mysteriously instructs CSCRIPT to interpret the script as WSF. Hopefully MicroSoft will never disable that "feature".
REM :: https://stackoverflow.com/questions/9074476/is-it-possible-to-embed-and-execute-vbscript-within-a-batch-file-without-using-a
if "%debugme%"=="yes" (
echo RefrEnv - Refresh the Environment for CMD - ^(Debug enabled^)
) else (
echo RefrEnv - Refresh the Environment for CMD
)
set "TEMPDir=%TEMP%\refrenv"
IF NOT EXIST "%TEMPDir%" mkdir "%TEMPDir%"
set "outputfile=%TEMPDir%\_NewEnv.cmd"
REM detect if DelayedExpansion is enabled
REM It relies on the fact, that the last caret will be removed only in delayed mode.
REM https://www.dostips.com/forum/viewtopic.php?t=6496
set "DelayedExpansionState=IsDisabled"
IF "^!" == "^!^" (
REM echo DelayedExpansion is enabled
set "DelayedExpansionState=IsEnabled"
)
REM :: generate %outputfile% which contain all the new variables
REM cscript //nologo "%~f0?.wsf" %1
cscript //nologo "%~f0?.wsf" "%outputfile%" %DelayedExpansionState%
REM ::set the new variables generated with vbscript script above
REM for this to work always it is necessary to use DisableDelayedExpansion or escape ! and ^ when using EnableDelayedExpansion, but this script already solve this, so no worry about that now, thanks to God
REM test it with some bad var like:
REM all 32 characters: ; & % ' ( ) ~ + @ # $ { } [ ] , ` ! ^ | > < \ / " : ? * = . - _ & echo baaaad
REM For /f delims^=^ eol^= %%a in (%outputfile%) do %%a
REM for /f "delims== tokens=1,2" %%G in (%outputfile%) do set "%%G=%%H"
For /f delims^=^ eol^= %%a in (%outputfile%) do set %%a
REM for safely print a variable with bad charachters do:
REM SETLOCAL EnableDelayedExpansion
REM echo "!z9!"
REM or
REM set z9
REM but generally paths and environment variables should not have bad metacharacters, but it is not a rule!
if "%debugme%"=="yes" (
explorer "%TEMPDir%"
) else (
rmdir /Q /S "%TEMPDir%"
)
REM cleanup
set "TEMPDir="
set "outputfile="
set "DelayedExpansionState="
set "debugme="
REM pause
exit /b
REM #############################################################################
REM :: to run jscript you have to put <script language="JScript"> directly after ----- Begin wsf script --->
----- Begin wsf script --->
<job><script language="VBScript">
REM #############################################################################
REM ### put you code here #######################################################
REM #############################################################################
REM based on itsadok script from here
REM https://stackoverflow.com/questions/171588/is-there-a-command-to-refresh-environment-variables-from-the-command-prompt-in-w
REM and it is faster as stated by this comment
REM While I prefer the Chocolatey code-wise for being pure batch code, overall I decided to use this one, since it's faster. (~0.3 seconds instead of ~1 second -- which is nice, since I use it frequently in my Explorer "start cmd here" entry) –
REM and it is safer based on my tests, the Chocolatey refreshenv is so bad if the variable have some cmd metacharacters
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
Set WshShell = WScript.CreateObject("WScript.Shell")
filename=WScript.Arguments.Item(0)
DelayedExpansionState=WScript.Arguments.Item(1)
TMPfilename=filename & "_temp_.cmd"
Set fso = CreateObject("Scripting.fileSystemObject")
Set tmpF = fso.CreateTextFile(TMPfilename, TRUE)
set oEnvS=WshShell.Environment("System")
for each sitem in oEnvS
tmpF.WriteLine(sitem)
next
SystemPath = oEnvS("PATH")
set oEnvU=WshShell.Environment("User")
for each sitem in oEnvU
tmpF.WriteLine(sitem)
next
UserPath = oEnvU("PATH")
set oEnvV=WshShell.Environment("Volatile")
for each sitem in oEnvV
tmpF.WriteLine(sitem)
next
VolatilePath = oEnvV("PATH")
set oEnvP=WshShell.Environment("Process")
REM i will not save the process env but only its path, because it have strange variables like =::=::\ and =F:=.... which seems to be added by vbscript
REM for each sitem in oEnvP
REM tmpF.WriteLine(sitem)
REM next
REM here we add the actual session path, so we do not reset the original path, because maybe the parent script added some folders to the path, If we need to reset the path then comment the following line
ProcessPath = oEnvP("PATH")
REM merge System, User, Volatile, and process PATHs
NewPath = SystemPath & ";" & UserPath & ";" & VolatilePath & ";" & ProcessPath
REM ________________________________________________________________
REM :: remove duplicates from path
REM :: expand variables so they become like windows do when he read reg and create path, then Remove duplicates without sorting
REM why i will clean the path from duplicates? because:
REM the maximum string length in cmd is 8191 characters. But string length doesnt mean that you can save 8191 characters in a variable because also the assignment belongs to the string. you can save 8189 characters because the remaining 2 characters are needed for "a="
REM based on my tests:
REM when i open cmd as user , windows does not remove any duplicates from the path, and merge system+user+volatil path
REM when i open cmd as admin, windows do: system+user path (here windows do not remove duplicates which is stupid!) , then it adds volatil path after removing from it any duplicates
REM ' https://www.rosettacode.org/wiki/Remove_duplicate_elements#VBScript
Function remove_duplicates(list)
arr = Split(list,";")
Set dict = CreateObject("Scripting.Dictionary")
REM ' force dictionary compare to be case-insensitive , uncomment to force case-sensitive
dict.CompareMode = 1
For i = 0 To UBound(arr)
If dict.Exists(arr(i)) = False Then
dict.Add arr(i),""
End If
Next
For Each key In dict.Keys
tmp = tmp & key & ";"
Next
remove_duplicates = Left(tmp,Len(tmp)-1)
End Function
REM expand variables
NewPath = WshShell.ExpandEnvironmentStrings(NewPath)
REM remove duplicates
NewPath=remove_duplicates(NewPath)
REM remove_duplicates() will add a ; to the end so lets remove it if the last letter is ;
If Right(NewPath, 1) = ";" Then
NewPath = Left(NewPath, Len(NewPath) - 1)
End If
tmpF.WriteLine("PATH=" & NewPath)
tmpF.Close
REM ________________________________________________________________
REM :: exclude setting variables which may be dangerous to change
REM when i run a script from task scheduler using SYSTEM user the following variables are the differences between the scheduler env and a normal cmd script, so i will not override those variables
REM APPDATA=D:\Users\LLED2\AppData\Roaming
REM APPDATA=D:\Windows\system32\config\systemprofile\AppData\Roaming
REM LOCALAPPDATA=D:\Users\LLED2\AppData\Local
REM LOCALAPPDATA=D:\Windows\system32\config\systemprofile\AppData\Local
REM TEMP=D:\Users\LLED2\AppData\Local\Temp
REM TEMP=D:\Windows\TEMP
REM TMP=D:\Users\LLED2\AppData\Local\Temp
REM TMP=D:\Windows\TEMP
REM USERDOMAIN=LLED2-PC
REM USERDOMAIN=WORKGROUP
REM USERNAME=LLED2
REM USERNAME=LLED2-PC$
REM USERPROFILE=D:\Users\LLED2
REM USERPROFILE=D:\Windows\system32\config\systemprofile
REM i know this thanks to this comment
REM The solution is good but it modifies env variables TEMP and TMP replacing them with values stored in HKCU\Environment. In my case I run the script to update env variables modified by Jenkins job on a slave that's running under SYSTEM account, so TEMP and TMP get substituted by %USERPROFILE%\AppData\Local\Temp instead of C:\Windows\Temp. This breaks build because linker cannot open system profile's Temp folder. – Gene Mayevsky Sep 26 '19 at 20:51
REM Delete Lines of a Text File Beginning with a Specified String
REM those are the variables which should not be changed by this script
arrBlackList = Array("ALLUSERSPROFILE=", "APPDATA=", "CommonProgramFiles=", "CommonProgramFiles(x86)=", "CommonProgramW6432=", "COMPUTERNAME=", "ComSpec=", "HOMEDRIVE=", "HOMEPATH=", "LOCALAPPDATA=", "LOGONSERVER=", "NUMBER_OF_PROCESSORS=", "OS=", "PATHEXT=", "PROCESSOR_ARCHITECTURE=", "PROCESSOR_ARCHITEW6432=", "PROCESSOR_IDENTIFIER=", "PROCESSOR_LEVEL=", "PROCESSOR_REVISION=", "ProgramData=", "ProgramFiles=", "ProgramFiles(x86)=", "ProgramW6432=", "PUBLIC=", "SystemDrive=", "SystemRoot=", "TEMP=", "TMP=", "USERDOMAIN=", "USERDOMAIN_ROAMINGPROFILE=", "USERNAME=", "USERPROFILE=", "windir=", "SESSIONNAME=")
Set objFS = CreateObject("Scripting.FileSystemObject")
Set objTS = objFS.OpenTextFile(TMPfilename, ForReading)
strContents = objTS.ReadAll
objTS.Close
TMPfilename2= filename & "_temp2_.cmd"
arrLines = Split(strContents, vbNewLine)
Set objTS = objFS.OpenTextFile(TMPfilename2, ForWriting, True)
REM this is the equivalent of findstr /V /I /L or grep -i -v , i don t know a better way to do it, but it works fine
For Each strLine In arrLines
bypassThisLine=False
For Each BlackWord In arrBlackList
If Left(UCase(LTrim(strLine)),Len(BlackWord)) = UCase(BlackWord) Then
bypassThisLine=True
End If
Next
If bypassThisLine=False Then
objTS.WriteLine strLine
End If
Next
REM ____________________________________________________________
REM :: expand variables because registry save some variables as unexpanded %....%
REM :: and escape ! and ^ for cmd EnableDelayedExpansion mode
set f=fso.OpenTextFile(TMPfilename2,ForReading)
REM Write file: ForAppending = 8 ForReading = 1 ForWriting = 2 , True=create file if not exist
set fW=fso.OpenTextFile(filename,ForWriting,True)
Do Until f.AtEndOfStream
LineContent = f.ReadLine
REM expand variables
LineContent = WshShell.ExpandEnvironmentStrings(LineContent)
REM _____this part is so important_____
REM if cmd delayedexpansion is enabled in the parent script which calls this script then bad thing happen to variables saved in the registry if they contain ! . if var have ! then ! and ^ are removed; if var do not have ! then ^ is not removed . to understand what happens read this :
REM how cmd delayed expansion parse things
REM https://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912
REM For each parsed token, first check if it contains any !. If not, then the token is not parsed - important for ^ characters. If the token does contain !, then scan each character from left to right:
REM - If it is a caret (^) the next character has no special meaning, the caret itself is removed
REM - If it is an exclamation mark, search for the next exclamation mark (carets are not observed anymore), expand to the value of the variable.
REM - Consecutive opening ! are collapsed into a single !
REM - Any remaining unpaired ! is removed
REM ...
REM Look at next string of characters, breaking before !, :, or <LF>, and call them VAR
REM conclusion:
REM when delayedexpansion is enabled and var have ! then i have to escape ^ and ! ,BUT IF VAR DO NOT HAVE ! THEN DO NOT ESCAPE ^ .this made me crazy to discover
REM when delayedexpansion is disabled then i do not have to escape anything
If DelayedExpansionState="IsEnabled" Then
If InStr(LineContent, "!") > 0 Then
LineContent=Replace(LineContent,"^","^^")
LineContent=Replace(LineContent,"!","^!")
End If
End If
REM __________
fW.WriteLine(LineContent)
Loop
f.Close
fW.Close
REM #############################################################################
REM ### end of vbscript code ####################################################
REM #############################################################################
REM this must be at the end for the hybrid trick, do not remove it
</script></job>
For cygwin/bash:
I cannot post it here I reached the post limit, so download it from here
call it from bash with: source refrenv.sh
For Powershell:
download it from here
Call it from Powershell with: . .\refrenv.ps1
I have changed the PATH variable in Windows 7.
However, when I open a command line window, and run
echo %path%
it still displays the old PATH.
How can I refresh PATH in the command line?
I can not restart or log out.
asked Nov 13, 2015 at 14:06
Changing any variable in one batch session wil not affect any other batch session.
You would need to use the setx
command (see setx /?
from the prompt) to make any change visible in any sessions that start after your setx
was executed.
set "path=%path%;abcd"
will append abcd
to the path variable (the PATH
variable is a set of directorynames separated by semicolons.)
setx path "%path%"
will assign the current value of path (%path%) as the value of path for all future instances for this user. %path%
is wuoted as it may contain spaces.
setx path "%path%" /m
will assign the current value of path (%path%) as the value of path for all future instances for all users of this machine.
answered Nov 13, 2015 at 14:17
MagooMagoo
77.5k8 gold badges63 silver badges85 bronze badges
2
Took this from the chocolatey repo, save it to anything you want .cmd and run it, it should refresh the paths right every single time without reboot, for some reason the other methods involving commands like SET PATH=%PATH%;C:\CmdShortcuts
did not work for me in the newest versions of win 10 and 11.
::
:: 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 "RefreshEnv.cmd only works from cmd.exe, please install the Chocolatey Profile to take advantage of refreshenv from PowerShell"
echo | set /p dummy="Refreshing environment variables from registry for cmd.exe. 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
:: capture user / architecture
SET "OriginalUserName=%USERNAME%"
SET "OriginalArchitecture=%PROCESSOR_ARCHITECTURE%"
:: Set these variables
call "%TEMP%\_env.cmd"
:: Cleanup
del /f /q "%TEMP%\_env.cmd" 2>nul
:: reset user / architecture
SET "USERNAME=%OriginalUserName%"
SET "PROCESSOR_ARCHITECTURE=%OriginalArchitecture%"
echo | set /p dummy="Finished."
echo .```
answered Dec 8, 2022 at 19:09
Does a path need to set as ‘System Variables’? If no, then you can set a path to User’s PATH variable instead.
You will need to close command prompt then reopen again.
Type below.
echo %PATH%,
It should update with new.
answered Jul 29, 2020 at 7:36
The answer above is very close, its missing a step and an update.
Step One
Add your Change to the Path
This is still valid:
set "path=%path%;abcd"
(you can also use the GUI «edit the system environment variable» to edit the PATH)
Step Two
were going to apply the change to the User Account as noted above:
setx path "%path%"
Step Three
this ware things change. when I ran his command line it looked it works however it does not. running the /? command wiht Setx this the command line we should be running:
SETX /S system /U user /P password MYPATH ^%PATH^%
the example i grabbed from Microsoft is also quite helpful:
setx /s computer1 /u maindom\hiropln /p p@ssW23 MYPATH %PATH%
This DOES set your Machine System Environment Variable via CMD. Personally, I find it easier in PowerShell. Have fun Scripting Kids! ;p
PS close and reopen your command shell to see the change
answered Aug 14, 2021 at 20:40
Kelly DavisKelly Davis
3542 silver badges6 bronze badges
1
Whilst I don’t have enough of a reputation to comment on the highest voted answer to this question, I would like to state that it is not exactly correct. I know this because no matter which workaround I tried in this post, nothing actually worked.
The kb article linked to in that answer actually states that:
However, note that modifications to the environment variables do not
result in immediate change. For example, if you start another Command
Prompt after making the changes, the environment variables will
reflect the previous (not the current) values. The changes do not take
effect until you log off and then log back on.
The part about the environment variables resetting to the previous values after reloading the command prompt is exactly what I experienced in Windows Server 2008.
The article goes on to say:
To effect these changes without having to log off, broadcast a WM_SETTINGCHANGE message to all windows in the system, so that any interested applications (such as Windows Explorer, Program Manager, Task Manager, Control Panel, and so forth) can perform an update.
That does not imply that Explorer broadcasts a WM_SETTINGCHANGE message once you have changed the system environment variables, or that it actually works. I’m not sure how you would do what is suggested in the KB article (to propagate the changes immediately) from the command prompt.