How to set a variable for the current OS session only - windows

setx permanently modifies environment variables.
set only makes variables available during batch script duration.
Is there any way to set a variable in order to hold its value until the system is restarted?
E.g. in my batch file, I'm checking if the variable is set like this:
if %MYVAR% == 1 (
<block>
)

#ECHO Off
IF NOT EXIST q25244121.org GOTO done
:: reset to original
FOR /f "tokens=1*delims==" %%a IN (q25244121.org) DO (
IF DEFINED %%a FOR /f "tokens=1*delims==" %%p IN ('set %%a') DO (
IF "%%a"=="%%p" IF "%%b" neq "%%q" SET "%%a=%%b"
)
)
:: Delete if not originally defined
FOR /f "tokens=1*delims==" %%p IN ('set') DO (
FINDSTR /L /i /c:"%%p=" q25244121.org >NUL
IF ERRORLEVEL 1 SET "%%p="
)
:done
:: Record current settings
set>q25244121.org
EXIT /b
This may work for you. You would need to change the SET instructions hown in CAPS to SETX. The tempfile would no doubt also need to be placed in a file where the username is part of the name you'd use.
If you were to include this batch in your startup directory, then it should restore the last-saved environment variables' values.
So, on first logon, the current variables' values are stored. On subsequent logons, the environment would be restored to those last stored, regardless of whether a setx had been executed.
You would however need to change procedures. This will restore to a known state. If you actually wanted to setx a value or install some software which adds new environment-variable values or changes existing ones (PATH would be favourite here) then you'd need to run this routine first, make the changes, delete the save file and re-run this routine. Awkward, I'll admit - but it's a way to do it.
Oh - and remember to set your variable after having setx it. You could even write a setxX batch to setx then set (or vice-versa) the required variable.

You may do that via a Batch-JScript hybrid script that use JScript's WshShell.Environment method. The documentation specify that there are four types of environments: System, User, Volatile and Process, and that Volatile type "Applies to current logon session and is not saved between logoffs and restarts", that is exactly what you want:
#if (#CodeSection == #Batch) #then
#echo off
rem Define a persistent variable for the current OS session only via JScript
Cscript //nologo //E:JScript "%~F0" MYVAR "This is the value"
goto :EOF
#end
var colEnvVars = WScript.CreateObject("WScript.Shell").Environment("Volatile");
colEnvVars(WScript.Arguments(0)) = WScript.Arguments(1);
You must save previous code in a .bat file and execute it as any Batch file. Note that the variable defined this way is not available in the current cmd.exe window, but only in future cmd.exe windows opened in the same OS session.
Tested on Windows 8.1.

Ok I found a much simpler (and obviously less hacky) way than the JScript method, but it put us in the right direction with the volatile environment manipulation.
Simply use the reg command to manipulate the volatile environment in the registry :
reg add "HKCU\Volatile Environment" /v "%MYVAR%" /d "%MYVALUE%" /f
reg add both can create and update the value.
\f bypasses the overwrite confirmation.
Setting an empty data with \d "" is equivalent to deleting the global variable. You won't see it in the shell with set, but you can still see it being empty in the registry.
Here is a reference: https://ss64.com/nt/reg.html

Related

How do I add a directory to User Environment Variables (PATH) without causing duplicates?

I'm trying to set up a script that will install python automatically, and I'm stuck on setting up the user path. I have only a vague clue about what I'm doing here so please excuse me if I'm using any terms incorrectly.
I'm trying to set the environment variables using setx path "%PATH%;%LOCALAPPDATA%\Programs\Python\Python310"\ but I've run into several issues.
I finally have this command not failing because of 'multiple default arguments' or something but now when trying to set PATH, I get duplicate entries.
If originally %PATH% gave me '\path1;\path2', and I run setx path "%PATH%;\path3", %PATH% outputs '\path1;\path2;\path1;\path2;\path3',
when I expected to have '\path1;\path2;\path3'
As per what I've been reading from other answers, I think %PATH% gives you the combined SYSTEM and USER paths, but setx path modifies the USER path only. So everytime I run setx path I'm adding the system variables again.
I just want to add my python.exe location to the user path variable in a .bat script without this duplicating issue. Does anyone have a working solution?
#ECHO OFF
SETLOCAL
SET "python=%%USERPROFILE%%\AppData\Local\Microsoft\WindowsApps"
ECHO %path%>u:\pp.txt
FOR /f "tokens=1,2,*" %%u IN ('reg query HKCU\Environment') DO IF "%%u"=="Path" (
FIND /v "%python%" "u:\pp.txt" >NUL
IF NOT ERRORLEVEL 1 (
ECHO CHANGE path
ECHO SETX PATH "%%w;%python%"
)
)
DEL u:\pp.txt
GOTO :EOF
I used a path that I have installed as python. Note that the % need to be doubled.
Write the current path to a tempfile (u:\pp.txt is simply on a RAMDRIVE for me)
Read the environment data from the registry, tokenise and select for the first item in %%u being Path. Its value will be in %%w.
See whether the "python path" is already in the path; if not, errorlevel will be 1 so execute the setx.
I merely echoed the setx as I'm not going to change the registry. If the command echoed appears correct, remove the echo to actually execute the setx.
It may be an idea to also set the path in the current environment, as setx changes the variable's value for future instances, not for the current one.
===== Revision ==== in the light of comments:
#ECHO Off
SETLOCAL
SET "python=%%USERPROFILE%%\AppData\Local\Microsoft\WindowsApps"
ECHO %path%>u:\pp.txt
FOR /f "tokens=1,2,*" %%u IN ('reg query HKCU\Environment') DO IF /i "%%u"=="Path" (
FIND /v "%python%" "u:\pp.txt" >NUL
IF NOT ERRORLEVEL 1 (
SETLOCAL ENABLEDELAYEDEXPANSION
SET "xpath=%%w;%python%"
SET "xpath=!xpath:~159!"
IF DEFINED xpath (ECHO PATH too long) ELSE (
ECHO CHANGE path
ECHO SETX %%u "%%w;%python%"
)
ENDLOCAL
)
)
DEL u:\pp*.txt
GOTO :EOF
Fixes:
Comparison in for ...%%u made case-insensitive.
Length of resultant user-path variable checked. I used a value of 159 for testing, 1022 for real-world.
variable name being setx'd will be identical to that retrieved from the registry. (For me, it's Path (W11 22H2) - My editor helpfully changes any batch keyword followed by a space to upper-case)

Question About Batch Variables and the Call Method

I am trying to figure out how to use call appropriately to pass variables backwards (to the original batch file that calls other batch files).
The way I have my batch files currently setup is my main batch file calls other batch files which may then even call a third batch file which creates the variable.
Here are some examples of my scripts so far, for this example I will be focusing on main.bat, VerifyCredentials.bat, and the CreateAdminCreds.bat files. In these I am trying to pass the %AdminUser% and %AdminPass% variables back to main.bat:
main.bat example:
REM Define all the variables that will be updated by other batch files.
set NewCompName= & set DomainUser= & set DomainPass= & set AdminUser= & set AdminPass=
REM Create the variables for the domain tech account and local admin account. Verify tech account can access SCCM file share.
set CredTestVar=0
:CredTestLoop
call CreateCompName.bat & call VerifyCredentials.bat & call TestCredentials.bat
if %CredTestVar% LSS 1 goto CredTestLoop
REM Activate the local admin account and set password
ECHO Enabling Administrator account
net user administrator /active:yes
net user administrator "%AdminPass%"
ECHO.
VerifyCredentials.bat example:
#ECHO off
if not exist Credentials\DomainUser.txt call CreateDomainCreds.bat
if not exist Credentials\DomainPass.txt call CreateDomainCreds.bat
for /f "delims=" %%x in (Credentials\DomainUser.txt) do set DomainUser=%%x
for /f "delims=" %%x in (Credentials\DomainPass.txt) do set DomainPass=%%x
if not exist Credentials\AdminUser.txt call CreateAdminCreds.bat
if not exist Credentials\AdminPass.txt call CreateAdminCreds.bat
for /f "delims=" %%x in (Credentials\AdminUser.txt) do set AdminUser=%%x
for /f "delims=" %%x in (Credentials\AdminPass.txt) do set AdminPass=%%x
CreateAdminCreds.bat example:
#ECHO off
REM Create and define the local administrator credentials
:CreateAdmin
cls
echo.
echo Please enter a new password for the local Administrator account
echo.
set "AdminUser=Administrator"
set /p "AdminPass=Administrator Password:"
goto :ResponseAdmin
:ResponseAdmin
set "AdminAnswer="
cls
echo.
echo The Administrator password is "%AdminPass%"
echo.
set /p "AdminAnswer=Is this correct? (y/n):"
if %AdminAnswer%==y () else (if %AdminAnswer%==n (goto :CreateAdmin) else (goto :ResponseAdmin))
(echo=%AdminUser%) > "Credentials\AdminUser.txt"
(echo=%AdminPass%) > "Credentials\AdminPass.txt"
set "AdminAnswer="
So all of this individually works fine.. but when I get to the step in main.bat where I try to use that variable %AdminPass% for the tech to define the local admin account it doesn't change the password to anything (on restart/lock you can login to local admin without a password)
Can anyone help explain to me why the variable %AdminPass% is not being passed back to main.bat?
I have tested this passing theory like this:
test1.bat
#ECHO off
set testvar=
echo testvar is currently equal to %testvar%
REM this returns "testvar is currently equal to"
call test2.bat
echo testvar is now equal to %testvar%
REM this returns "testvar is now equal to something"
test2.bat
#ECHO off
set testvar="something"
and this successfully changes testvar to something for the second echo in the test1.bat file.
Thank you in advance for any help.
When a cmd instance starts, it is provided with a set of string variables which form the environment (always strings - if the value of any string is all-numeric, then it can often be used in calculations.)
Any batch file that runs within that instance can modify, add to, or delete variables. Hence running batch files A and B in that order would allow B to see values established by A, but in the reverse order, those values would not be set.
It's therefore usual practice to follow the initial #echo off command (which turns command-regurgitation to the console for debugging OFF) by a setlocal command, which itself has various options. Fundamentally, a setlocal establishes a local environment with a copy of the environment as it stood when the setlocal was executed.
setlocals may be nested, and are closed by an endlocal command or by reaching the physical end-of-file, whereupon the environment is restored to its condition at the time the matching setlocal was executed. Note that this applies only to the environment, it does not affect the setting of the durrent directory or drive for instance.
So, if A calls B then B will NOT manipulate A's environment if B uses setlocal. If B has no setlocal then it will manipulate A's environment BUT if run from the prompt, it will manipulate the cmd instance's environment, which is generally undesirable.
There is a method to transmit the variable "over the endlocal barrier" like this:
endlocal&set "fred=%fred%"
which seems quite bizarre. What this does is use cmd's parser. The entire line is parsed, and %fred% is replaced by the current value of the variable fred within the inner environment, and then the line endlocal&set "fred=fredsvalue" is executed; two commands, serially. So the inner environment is discarded and then the variable in the calling environment is set to the value.
So - you pays your money, you takes your choice. Use setlocal in the called routines, and you'll need to jump the endlocal barriers. Omit the setlocal and the called routine will manipulate the current environment.

How is it possible to get Windows default user profile path via CMD?

Windows default user profile is usually %SystemDrive%\users\default but its real location is not an environment variable but it can be useful to have it.
Default user profile path can be detected by system registry query like that
#echo off
for /f "tokens=2*" %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\MICROSOFT\WINDOWS NT\CurrentVersion\ProfileList" /v "Default"') do set "defaultuserprofile=%%b"
echo %defaultuserprofile%
pause
But we get the value %SystemDrive%\Users\Default where %SystemDrive% is not converted to C: (or other letter) so environment variable %defaultuserprofile% can not be used as normal environment variable path for file operations.
Alternative variant can be something like
#echo off
cd /d "%public%"
cd ..\
set usersdir=%cd%
set defaultuserprofile=%usersdir%\default
echo %defaultuserprofile%
pause
But it seems to be not so good.
So how is it possible to get Windows default user profile path via CMD?
Don't your really want %PUBLIC%, which is C:\Users\Public? At least that's closest equivalent on Windows 10 to a "Default" folder.
#echo off
setlocal
set "defaultuserprofile="
for /f "tokens=1,2,*" %%A in ('reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList" /v "Default"') do (
if "%%~A" == "Default" call set "defaultuserprofile=%%C"
)
echo "%defaultuserprofile%"
pause
The type of the data is REG_EXPAND_SZ. To expand the %SystemDrive% embedded in the string, use call set. call causes another parse of the command so that set assigns C:\ instead of %SystemDrive%.
Like the 2nd OP code, which is not as reliable as the reg query:
#echo off
cd /d "%Public%\..\Default" || exit /b 1
echo "%cd%"
pause
If you want to view the Default folder and other hidden folders in the Users directory, use:
dir /a:h
Output is the symlink named All Users, the folder named Default and the symlink named Default User on Windows 10 v1903.
Firstly, just to mention the purpose of the Default user profile is as the basis for all new user profiles. Therefore it should be used only to configure applications, settings and customizations for each future new user account on the PC. (modifications within it do not propagate to existing users).
The following method is similar to the existing answer, in that an additional expansion is used to cater for any variables within the contained data string. Please note that the value type of the data is by default REG_EXPAND_SZ, but it can also be of type REG_SZ, (the expand type is only necessary if the string contains a variable).
#Echo Off
Set "RKey=HKLM\Software\Microsoft\Windows NT\CurrentVersion\ProfileList"
Set "RVal=Default"
Set "ProfilePath="
For /F "Tokens=2*" %%G In (
'""%__APPDIR__%reg.exe" Query "%RKey%" /V "%RVal%" 2>NUL|"%__APPDIR__%find.exe" /I "%RVal%""'
)Do For /F "Tokens=*" %%I In ('Echo("%%~H"')Do Set "ProfilePath=%%~I"
If Not Defined ProfilePath Exit /B 1
Rem Your code using "%ProfilePath%" goes below here
Echo "%ProfilePath%" & Pause
I have Remarked a line with comment, which can be optionally omitted, and provided an example line below it for demonstration purposes, please modify that as necessary.
The code uses full paths for all external commands, (via a special variable, %__APPDIR__%, which will always point to their correct location). I have done that in order to remove any reliance on the content of the editable environment variables %PATH% and %PATHEXT%, (deliberate, or accidental, modification of those two environment variables could otherwise break the code).

Remove unwanted path name from %path% variable via batch

Scope: Windows XP or newer
Tools: Batch script
I need to be able to remove an unneeded path name from the system %PATH% variable. I know how to add a new path name to the system %PATH% variable, using a tool such as SETX.EXE, which also makes it immediately available within the existing CMD environment. It's probably a matter of using FIND and/or a FOR loop of some kind, but I'm not quite sure how to accomplish this. Here's a sample path statement...
%PATH% = C:\;C:\Program Files\Common Files\Java;C:\oracle\product\10.2.0\bin;C:\WINDOWS;C:\WINDOWS\system32;
From this, I need to be able to remove the full path name related to "oracle." So, in the above example, I need to be able to remove the "C:\oracle\product\10.2.0\bin" from the above path statement. Unfortunately, not only could the oracle path name be different than shown above, there could be multiple oracle path names and all need to be removed. I tried implementing the solution here...
How can I extract a full path from the PATH environment variable?
However, it just isn't working. The script wouldn't find the path name. Any help would be appreciated. Thank you.
This removes the substring C:\Program Files (x86)\Git\bin; from the PATH string and re-assigns:
set PATH=%PATH:C:\Program Files (x86)\Git\bin;=%
You might use this to see the change:
echo %PATH:C:\Program Files (x86)\Git\bin;=% | tr ; \n
Note: be exact on the substring. It's case-sensitive and slash-sensitive.
If you need to make it a persistent change use setx instead of set and open another console for changes to take effect.
setx /M PATH "%PATH:C:\Program Files (x86)\Git\bin;=%"
You can try something like this :
#echo off&cls
setlocal EnableDelayedExpansion
set $line=%path%
set $line=%$line: =#%
set $line=%$line:;= %
for %%a in (%$line%) do echo %%a | find /i "oracle" || set $newpath=!$newpath!;%%a
set $newpath=!$newpath:#= !
echo set path=!$newpath:~1!
I putted an echo to the last line. Check the result and If it's OK for you, remove it.
After trying SachaDee's answers I got errors with paths like
C:\Program Files (x86)
with brackets:
Program Files (x86)\Directory
gave me
Directorywas unexpected at this time. (no matter what time I tried it)
I added
set $line=%$line:)=^^)%
before the for-loop and
set $newpath=!$newpath:^^=!
after the loop (not sure if it is necessary)
#echo off
setlocal EnableDelayedExpansion
set path
set $line=%path%
set $line=%$line: =#%
set $line=%$line:;= %
set $line=%$line:)=^^)%
for %%a in (%$line%) do echo %%a | find /i "oracle" || set $newpath=!$newpath!;%%a
set $newpath=!$newpath:#= !
set $newpath=!$newpath:^^=!
set path=!$newpath:~1!
And it is now working.
I found the other solutions to this problem a bit awkward, I don't really want to rely on exact paths, complex 'delayed expansion' syntax, removing spaces for the 'for /f' loop and then adding them back in...
I think this is more elegant, and I commented the hell out of it so even someone new to the horrors of Batch can follow along.
::Turn off command display and allows environmental variables to be overridden for the current session
#echo off & setlocal
::Creates a unique file to use for the 'for loop'
set "TMPFILE="%temp%\tmp%RANDOM%%RANDOM%.txt""
::Duplicate PATH into OLDPATH
set "OLDPATH=%PATH%"
::Declare label for the 'goto' command
:Loop
::Extract the first text token with the default delimiter of semicolon
for /f "tokens=1 delims=;" %%G in ("%OLDPATH%") do (
REM Copy text token to TMPFILE unless what we want to remove is found
<NUL set /p="%%G" | find /i "StRiNgThAtMaTcHeSwHaTtOrEmOvE" >NUL 2>&1 || <NUL set /p="%%G;" >>%TMPFILE%
REM Remove text token from OLDPATH
set "OLDPATH=%OLDPATH:*;=%"
)
::Repeat loop until OLDPATH no longer has any delimiters, and then add any remaining value to TMPFILE
echo %OLDPATH% | findstr /C:";" >NUL && (goto :Loop) || <NUL set /p="%OLDPATH%" >>%TMPFILE%
::Set the path to TMPFILE
for /f "usebackq delims=" %%G in (%TMPFILE%) do (set "PATH=%%G")
::Clean-up
del %TMPFILE% >NUL 2>&1
::An echo and pause just for debug purposes
echo %PATH%
pause
I use this in CYGWIN to filter out CYGWIN paths before starting some Windows commands:
export PATH=`perl -e '#a=grep {$_ =~ /^\/cygdrive\//} split(":", $ENV{PATH});print join(":",#a)'`
I'm quite sure it's easy to adapt to Windows-native perl and bat files. Advantage: the flexible power of regular expressions.
I wanted to remove %LocalAppData%\Microsoft\WindowsApps; from PATH. But this was not possible due to using a another variable in the environment variable for Windows. The CALL hack is worked in SS64. (Also, thanks to Jens A. Koch for the base command.)
CALL set PATH=%PATH:%LocalAppData%\Microsoft\WindowsApps;=%
Of course, the PATH changing by SET will not be permanent. For fixed change, it is necessary to use the SETX command or directly change the entries in the Registry.
Actually, this solution was not needed to delete %LocalAppData%\Microsoft\WindowsApps; from PATH.
The %LocalAppData%\Microsoft\WindowsApps; is stored in the PATH entry of the Registry's HKCU\Environment key. Although it is more practical to delete this entry with the REG DELETE command, if there are another directories in the PATH entry, they will also be deleted, so new solution is needed.
I failed to remove the %USERPROFILE% variable syntax from SET (The %% symbol dilemma). Fortunately, PShell came to the rescue:
SET userprofile=
Powershell -c "$UserEnvironmentPath = [System.Environment]::GetEnvironmentVariable('Path', 'User'); $UserEnvironmentPath = $UserEnvironmentPath.Replace('%USERPROFILE%\AppData\Local\Microsoft\WindowsApps;',''); [Microsoft.Win32.Registry]::SetValue('HKEY_CURRENT_USER\Environment', 'Path', $UserEnvironmentPath, [Microsoft.Win32.RegistryValueKind]::ExpandString)"
Special thanks to vonpryz for the last command. Because PowerShell's [System.Environment]::SetEnvironmentVariable command saves variables to Registry as REG_SZ even if their original value type is REG_EXPAND_SZ, which it's the known issue.
I wrote this code to simply remove any python executeable path from the path variable,
and insert my own specefic python version in the path so i can run python with
the versoin i wanted.
setlocal enableDelayedExpansion
set path`enter code here`
set $line=%path%
set $line=%$line: =#%
set $line=%$line:;= %
set $line=%$line:)=^^)%
set newpath=
for %%a in (%$line%) do (
echo %%a | find /i "python" ||set newpath=!newpath!;%%a
)
set path=!newpath!
set PATH=D:\python2.7\;%PATH%
#REM Rest of your script
python --version
#REM to exit the batch but not the window
exit /b
also, the first line is important! don't remove it or it wont work.
Notice: this code must run from a batch ".bat" file , if u want to copy paste this code in cmd window, you must replace all "%%a" to "%a" in this code.
If you know a file that exists within the directory you want to remove (e.g. want to remove all paths that might include java.exe), the following will work very straightforwardly by simply doing string replacement, no need to parse the path, etc:
#REM Executable to look for
set CMD=java.exe
:search
#REM Find the executable anywhere in the path
for %%a in (%CMD%) do set FOUND=%%~$PATH:a
if "%FOUND%"=="" goto done
#REM Strip \cmd.ext so we just have the directory
set FOUND=!FOUND:\%CMD%=!
#echo Found %CMD% in %FOUND%
#echo Removing %FOUND% from path...
set "PATH=!PATH:%FOUND%=!"
#REM Clean up any lone leftover \ in the path (in case the path was C:\foo\ instead of C:\foo)
set PATH=%PATH:;\;=;%
goto search
:done

Is there a command to refresh environment variables from the command prompt in Windows?

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?
On Windows 7/8/10, you can install Chocolatey, which has a script for this built-in.
After installing Chocolatey, just type RefreshEnv.cmd.
Here is what Chocolatey uses.
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 "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 .
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.
Create a file named resetvars.vbs containing this code, and save it on the path:
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:
#echo off
%~dp0resetvars.vbs
call "%TEMP%\resetvars.bat"
When you want to refresh the environment variables, just run 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
b. the PATH environment variable is a concatenation of the user and the system PATH variables.
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.
I use the weird vbs+bat+temporary bat mechanism to work around the problem of exporting variables from 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):
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:
"%TEMP%\resetvars.bat"
By design there isn't a built in mechanism 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".
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.
The latest accepted answer shows a partial work-around by manually refreshing all the 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.
I came across this answer before eventually finding an easier solution.
Simply restart explorer.exe in Task Manager.
I didn't test, but you may also need to reopen you command prompt.
Credit to Timo Huovinen here: Node not recognized although successfully installed (if this helped you, please go give this man's comment credit).
This works on 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 :)
Use "setx" and restart cmd prompt
There is a command line tool named "setx" for this job.
It's for reading and writing env variables.
The variables persist after the command window has been closed.
It "Creates or modifies environment variables in the user or system environment, without requiring programming or scripting. The setx command also retrieves the values of registry keys and writes them to text files."
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.
If setx is missing:
http://download.microsoft.com/download/win2000platform/setx/1.00.0.1/nt5/en-us/setx_setup.exe
Or modify the registry
MSDN says:
To programmatically add or modify system environment variables, add
them to the
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session
Manager\Environment registry key, then broadcast a WM_SETTINGCHANGE
message with lParam set to the string "Environment".
This allows applications, such as the shell, to pick up your updates.
Calling this function has worked for me:
VOID Win32ForceSettingsChange()
{
DWORD dwReturnValue;
::SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM) "Environment", SMTO_ABORTIFHUNG, 5000, &dwReturnValue);
}
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
Orginal Batch calls to new Batch:
testenvget.cmd SDROOT (or whatever the variable)
#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....\
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
Restarting explorer did this for me, but only for new cmd terminals.
The terminal I set the path could see the new Path variable already (in Windows 7).
taskkill /f /im explorer.exe && explorer.exe
It is possible to do this by overwriting the Environment Table within a specified process itself.
As a proof of concept I wrote this sample app, which just edited a single (known) environment variable in a cmd.exe process:
typedef DWORD (__stdcall *NtQueryInformationProcessPtr)(HANDLE, DWORD, PVOID, ULONG, PULONG);
int __cdecl main(int argc, char* argv[])
{
HMODULE hNtDll = GetModuleHandleA("ntdll.dll");
NtQueryInformationProcessPtr NtQueryInformationProcess = (NtQueryInformationProcessPtr)GetProcAddress(hNtDll, "NtQueryInformationProcess");
int processId = atoi(argv[1]);
printf("Target PID: %u\n", processId);
// open the process with read+write access
HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_VM_OPERATION, 0, processId);
if(hProcess == NULL)
{
printf("Error opening process (%u)\n", GetLastError());
return 0;
}
// find the location of the PEB
PROCESS_BASIC_INFORMATION pbi = {0};
NTSTATUS status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
if(status != 0)
{
printf("Error ProcessBasicInformation (0x%8X)\n", status);
}
printf("PEB: %p\n", pbi.PebBaseAddress);
// find the process parameters
char *processParamsOffset = (char*)pbi.PebBaseAddress + 0x20; // hard coded offset for x64 apps
char *processParameters = NULL;
if(ReadProcessMemory(hProcess, processParamsOffset, &processParameters, sizeof(processParameters), NULL))
{
printf("UserProcessParameters: %p\n", processParameters);
}
else
{
printf("Error ReadProcessMemory (%u)\n", GetLastError());
}
// find the address to the environment table
char *environmentOffset = processParameters + 0x80; // hard coded offset for x64 apps
char *environment = NULL;
ReadProcessMemory(hProcess, environmentOffset, &environment, sizeof(environment), NULL);
printf("environment: %p\n", environment);
// copy the environment table into our own memory for scanning
wchar_t *localEnvBlock = new wchar_t[64*1024];
ReadProcessMemory(hProcess, environment, localEnvBlock, sizeof(wchar_t)*64*1024, NULL);
// find the variable to edit
wchar_t *found = NULL;
wchar_t *varOffset = localEnvBlock;
while(varOffset < localEnvBlock + 64*1024)
{
if(varOffset[0] == '\0')
{
// we reached the end
break;
}
if(wcsncmp(varOffset, L"ENVTEST=", 8) == 0)
{
found = varOffset;
break;
}
varOffset += wcslen(varOffset)+1;
}
// check to see if we found one
if(found)
{
size_t offset = (found - localEnvBlock) * sizeof(wchar_t);
printf("Offset: %Iu\n", offset);
// write a new version (if the size of the value changes then we have to rewrite the entire block)
if(!WriteProcessMemory(hProcess, environment + offset, L"ENVTEST=def", 12*sizeof(wchar_t), NULL))
{
printf("Error WriteProcessMemory (%u)\n", GetLastError());
}
}
// cleanup
delete[] localEnvBlock;
CloseHandle(hProcess);
return 0;
}
Sample output:
>set ENVTEST=abc
>cppTest.exe 13796
Target PID: 13796
PEB: 000007FFFFFD3000
UserProcessParameters: 00000000004B2F30
environment: 000000000052E700
Offset: 1528
>set ENVTEST
ENVTEST=def
Notes
This approach would also be limited to security restrictions. If the target is run at higher elevation or a higher account (such as SYSTEM) then we wouldn't have permission to edit its memory.
If you wanted to do this to a 32-bit app, the hard coded offsets above would change to 0x10 and 0x48 respectively. These offsets can be found by dumping out the _PEB and _RTL_USER_PROCESS_PARAMETERS structs in a debugger (e.g. in WinDbg dt _PEB and dt _RTL_USER_PROCESS_PARAMETERS)
To change the proof-of-concept into a what the OP needs, it would just enumerate the current system and user environment variables (such as documented by #tsadok's answer) and write the entire environment table into the target process' memory.
Edit: The size of the environment block is also stored in the _RTL_USER_PROCESS_PARAMETERS struct, but the memory is allocated on the process' heap. So from an external process we wouldn't have the ability to resize it and make it larger. I played around with using VirtualAllocEx to allocate additional memory in the target process for the environment storage, and was able to set and read an entirely new table. Unfortunately any attempt to modify the environment from normal means will crash and burn as the address no longer points to the heap (it will crash in RtlSizeHeap).
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.
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.
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 chocolatey refreshenv 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
Environment variables are kept in HKEY_LOCAL_MACHINE\SYSTEM\ControlSet\Control\Session Manager\Environment.
Many of the useful env vars, such as Path, are stored as REG_SZ. There are several ways to access the registry including REGEDIT:
REGEDIT /E <filename> "HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Environment"
The output starts with magic numbers. So to search it with the find command it needs to be typed and redirected: type <filename> | findstr -c:\"Path\"
So, if you just want to refresh the path variable in your current command session with what's in system properties the following batch script works fine:
RefreshPath.cmd:
#echo off
REM This solution requests elevation in order to read from the registry.
if exist %temp%\env.reg del %temp%\env.reg /q /f
REGEDIT /E %temp%\env.reg "HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Environment"
if not exist %temp%\env.reg (
echo "Unable to write registry to temp location"
exit 1
)
SETLOCAL EnableDelayedExpansion
for /f "tokens=1,2* delims==" %%i in ('type %temp%\env.reg ^| findstr -c:\"Path\"=') do (
set upath=%%~j
echo !upath:\\=\! >%temp%\newpath
)
ENDLOCAL
for /f "tokens=*" %%i in (%temp%\newpath) do set path=%%i
Try opening a new command prompt as an administrator. This worked for me on Windows 10. (I know this is an old answer, but I had to share this because having to write a VBS script just for this is absurd).
The confusing thing might be that there are a few places to start the cmd from.
In my case I ran 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.
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.
Once I did this I had access to the new environment variable from a cmd that was spawned from windows explorer.
I use the following code in my batch scripts:
if not defined MY_ENV_VAR (
setx MY_ENV_VAR "VALUE" > nul
set MY_ENV_VAR=VALUE
)
echo %MY_ENV_VAR%
By using SET after SETX it is possible to use the "local" variable directly without restarting the command window. And on the next run, the enviroment variable will be used.
If it concerns just one (or a few) specific vars you want to change, I think the easiest way is a workaround: just set in in your environment AND in your current console session
Set will put the var in your current session
SetX will put the var in the environment, but NOT in your current session
I have this simple batch script to change my Maven from Java7 to Java8 (which are both env. vars) The batch-folder is in my PATH var so I can always call 'j8' and within my console and in the environment my JAVA_HOME var gets changed:
j8.bat:
#echo off
set JAVA_HOME=%JAVA_HOME_8%
setx JAVA_HOME "%JAVA_HOME_8%"
Till now I find this working best and easiest.
You probably want this to be in one command, but it simply isn't there in Windows...
The solution I've been using for a few years now:
#echo off
rem Refresh PATH from registry.
setlocal
set USR_PATH=
set SYS_PATH=
for /F "tokens=3* skip=2" %%P in ('%SystemRoot%\system32\reg.exe query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v PATH') do #set "SYS_PATH=%%P %%Q"
for /F "tokens=3* skip=2" %%P in ('%SystemRoot%\system32\reg.exe query "HKCU\Environment" /v PATH') do #set "USR_PATH=%%P %%Q"
if "%SYS_PATH:~-1%"==" " set "SYS_PATH=%SYS_PATH:~0,-1%"
if "%USR_PATH:~-1%"==" " set "USR_PATH=%USR_PATH:~0,-1%"
endlocal & call set "PATH=%SYS_PATH%;%USR_PATH%"
goto :EOF
Edit: Woops, here's the updated version.
I liked the approach followed by chocolatey, as posted in anonymous coward's answer, since it is a pure batch approach. However, it leaves a temporary file and some temporary variables lying around. I made a cleaner version for myself.
Make a file refreshEnv.bat somewhere on your PATH. Refresh your console environment by executing refreshEnv.
#ECHO OFF
REM Source found on https://github.com/DieterDePaepe/windows-scripts
REM Please share any improvements made!
REM Code inspired by http://stackoverflow.com/questions/171588/is-there-a-command-to-refresh-environment-variables-from-the-command-prompt-in-w
IF [%1]==[/?] GOTO :help
IF [%1]==[/help] GOTO :help
IF [%1]==[--help] GOTO :help
IF [%1]==[] GOTO :main
ECHO Unknown command: %1
EXIT /b 1
:help
ECHO Refresh the environment variables in the console.
ECHO.
ECHO refreshEnv Refresh all environment variables.
ECHO refreshEnv /? Display this help.
GOTO :EOF
:main
REM Because the environment variables may refer to other variables, we need a 2-step approach.
REM One option is to use delayed variable evaluation, but this forces use of SETLOCAL and
REM may pose problems for files with an '!' in the name.
REM The option used here is to create a temporary batch file that will define all the variables.
REM Check to make sure we don't overwrite an actual file.
IF EXIST %TEMP%\__refreshEnvironment.bat (
ECHO Environment refresh failed!
ECHO.
ECHO This script uses a temporary file "%TEMP%\__refreshEnvironment.bat", which already exists. The script was aborted in order to prevent accidental data loss. Delete this file to enable this script.
EXIT /b 1
)
REM Read the system environment variables from the registry.
FOR /F "usebackq tokens=1,2,* skip=2" %%I IN (`REG QUERY "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"`) DO (
REM /I -> ignore casing, since PATH may also be called Path
IF /I NOT [%%I]==[PATH] (
ECHO SET %%I=%%K>>%TEMP%\__refreshEnvironment.bat
)
)
REM Read the user environment variables from the registry.
FOR /F "usebackq tokens=1,2,* skip=2" %%I IN (`REG QUERY HKCU\Environment`) DO (
REM /I -> ignore casing, since PATH may also be called Path
IF /I NOT [%%I]==[PATH] (
ECHO SET %%I=%%K>>%TEMP%\__refreshEnvironment.bat
)
)
REM PATH is a special variable: it is automatically merged based on the values in the
REM system and user variables.
REM Read the PATH variable from the system and user environment variables.
FOR /F "usebackq tokens=1,2,* skip=2" %%I IN (`REG QUERY "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v PATH`) DO (
ECHO SET PATH=%%K>>%TEMP%\__refreshEnvironment.bat
)
FOR /F "usebackq tokens=1,2,* skip=2" %%I IN (`REG QUERY HKCU\Environment /v PATH`) DO (
ECHO SET PATH=%%PATH%%;%%K>>%TEMP%\__refreshEnvironment.bat
)
REM Load the variable definitions from our temporary file.
CALL %TEMP%\__refreshEnvironment.bat
REM Clean up after ourselves.
DEL /Q %TEMP%\__refreshEnvironment.bat
ECHO Environment successfully refreshed.
Thank you for posting this question which is quite interesting, even in 2019 (Indeed, it is not easy to renew the shell cmd since it is a single instance as mentioned above), because renewing environment variables in windows allows to accomplish many automation tasks without having to manually restart the command line.
For example, we use this to allow software to be deployed and configured on a large number of machines that we reinstall regularly. And I must admit that having to restart the command line during the deployment of our software would be very impractical and would require us to find workarounds that are not necessarily pleasant.
Let's get to our problem.
We proceed as follows.
1 - We have a batch script that in turn calls a powershell script like this
[file: task.cmd].
cmd > powershell.exe -executionpolicy unrestricted -File C:\path_here\refresh.ps1
2 - After this, the refresh.ps1 script renews the environment variables using registry keys (GetValueNames(), etc.).
Then, in the same powershell script, we just have to call the new environment variables available.
For example, in a typical case, if we have just installed nodeJS before with cmd using silent commands, after the function has been called, we can directly call npm to install, in the same session, particular packages like follows.
[file: refresh.ps1]
function Update-Environment {
$locations = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment',
'HKCU:\Environment'
$locations | ForEach-Object {
$k = Get-Item $_
$k.GetValueNames() | ForEach-Object {
$name = $_
$value = $k.GetValue($_)
if ($userLocation -and $name -ieq 'PATH') {
$env:Path += ";$value"
} else {
Set-Item -Path Env:\$name -Value $value
}
}
$userLocation = $true
}
}
Update-Environment
#Here we can use newly added environment variables like for example npm install..
npm install -g create-react-app serve
Once the powershell script is over, the cmd script goes on with other tasks.
Now, one thing to keep in mind is that after the task is completed, cmd has still no access to the new environment variables, even if the powershell script has updated those in its own session. Thats why we do all the needed tasks in the powershell script which can call the same commands as cmd of course.
There is no straight way, as Kev said. In most cases, it is simpler to spawn another CMD box. More annoyingly, running programs are not aware of changes either (although IIRC there might be a broadcast message to watch to be notified of such change).
It have been worse: in older versions of Windows, you had to log off then log back to take in account the changes...
I use this Powershell script to add to the PATH variable.
With a little adjustment it can work in your case too I believe.
#REQUIRES -Version 3.0
if (-not ("win32.nativemethods" -as [type])) {
# import sendmessagetimeout from win32
add-type -Namespace Win32 -Name NativeMethods -MemberDefinition #"
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern IntPtr SendMessageTimeout(
IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam,
uint fuFlags, uint uTimeout, out UIntPtr lpdwResult);
"#
}
$HWND_BROADCAST = [intptr]0xffff;
$WM_SETTINGCHANGE = 0x1a;
$result = [uintptr]::zero
function global:ADD-PATH
{
[Cmdletbinding()]
param (
[parameter(Mandatory=$True, ValueFromPipeline=$True, Position=0)]
[string] $Folder
)
# See if a folder variable has been supplied.
if (!$Folder -or $Folder -eq "" -or $Folder -eq $null) {
throw 'No Folder Supplied. $ENV:PATH Unchanged'
}
# Get the current search path from the environment keys in the registry.
$oldPath=$(Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH).Path
# See if the new Folder is already in the path.
if ($oldPath | Select-String -SimpleMatch $Folder){
return 'Folder already within $ENV:PATH'
}
# Set the New Path and add the ; in front
$newPath=$oldPath+';'+$Folder
Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH -Value $newPath -ErrorAction Stop
# Show our results back to the world
return 'This is the new PATH content: '+$newPath
# notify all windows of environment block change
[win32.nativemethods]::SendMessageTimeout($HWND_BROADCAST, $WM_SETTINGCHANGE, [uintptr]::Zero, "Environment", 2, 5000, [ref]$result)
}
function global:REMOVE-PATH {
[Cmdletbinding()]
param (
[parameter(Mandatory=$True, ValueFromPipeline=$True, Position=0)]
[String] $Folder
)
# See if a folder variable has been supplied.
if (!$Folder -or $Folder -eq "" -or $Folder -eq $NULL) {
throw 'No Folder Supplied. $ENV:PATH Unchanged'
}
# add a leading ";" if missing
if ($Folder[0] -ne ";") {
$Folder = ";" + $Folder;
}
# Get the Current Search Path from the environment keys in the registry
$newPath=$(Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH).Path
# Find the value to remove, replace it with $NULL. If it's not found, nothing will change and you get a message.
if ($newPath -match [regex]::Escape($Folder)) {
$newPath=$newPath -replace [regex]::Escape($Folder),$NULL
} else {
return "The folder you mentioned does not exist in the PATH environment"
}
# Update the Environment Path
Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH -Value $newPath -ErrorAction Stop
# Show what we just did
return 'This is the new PATH content: '+$newPath
# notify all windows of environment block change
[win32.nativemethods]::SendMessageTimeout($HWND_BROADCAST, $WM_SETTINGCHANGE, [uintptr]::Zero, "Environment", 2, 5000, [ref]$result)
}
# Use ADD-PATH or REMOVE-PATH accordingly.
#Anything to Add?
#Anything to Remove?
REMOVE-PATH "%_installpath_bin%"
Edit: this only works if the environment changes you're doing are as a result of running a batch file.
If a batch file begins with SETLOCAL then it will always unravel back to your original environment on exit even if you forget to call ENDLOCAL before the batch exits, or if it aborts unexpectedly.
Almost every batch file I write begins with SETLOCAL since in most cases I don't want the side-effects of environment changes to remain. In cases where I do want certain environment variable changes to propagate outside the batch file then my last ENDLOCAL looks like this:
ENDLOCAL & (
SET RESULT1=%RESULT1%
SET RESULT2=%RESULT2%
)
To solve this I have changed the environment variable using BOTH setx and set, and then restarted all instances of explorer.exe. This way any process subsequently started will have the new environment variable.
My batch script to do this:
setx /M ENVVAR "NEWVALUE"
set ENVVAR="NEWVALUE"
taskkill /f /IM explorer.exe
start explorer.exe >nul
exit
The problem with this approach is that all explorer windows that are currently opened will be closed, which is probably a bad idea - But see the post by Kev to learn why this is necessary
I just wanted to state that, those who use Anaconda, when you use the chocolatey Refreshenv command; all the environment variables associated with conda will be lost.
To counter this, the best way is to restart CMD. :(
This doesn't directly answer your question but if you just want interprocess communication, and you can use PowerShell, you can just use the Clipboard.
In one process
Set-Clipboard("MyText")
In separate process
$clipValue=Get-Clipboard
then you can use clipValue as any other string. This actually give you the ability to send the entire list of environment variables to another process using a CSV text string
More than likely, you are wanting your updated Environment Variables to be accessible by an Application that you have open and/or are running. As such, your best and easiest course of action is to simply close/re-open your application so that it picks up your updated Environment Variables.
The details behind the scenes are very nuanced, but the above should work for most use cases.

Resources