So, I have this batch file that supposedly appends my script to the path variable
@echo OFF
setx path "%path%;%cd%\\script.py"
But I e
Next script shows a possible approach.
@ECHO OFF >NUL
SETLOCAL enableextensions
rem enabledelayedexpansion
echo adding "%~1" to the user level HKCU\Environment /v Path
call :showReg old
call set "expanded=%~1"
if "%expanded%"=="" goto :usage
if not exist "%expanded%\" goto :usage
set "HKCU_type=REG_EXPAND_SZ"
set "HKCU_path="
for /F "tokens=1,2*" %%F in ('
reg query HKCU\Environment /v Path 2^>NUL ^|findstr /I "path"
') do (
set "HKCU_path=%%H"
REG ADD HKCU\Environment /v Path /t %HKCU_type% /d %%H;%~1 /f >NUL
)
if not defined HKCU_path (
REG ADD HKCU\Environment /v Path /t %HKCU_type% /d %~1 /f >NUL
)
:endlocal
call :showReg new
ENDLOCAL
goto :eof
:usage
echo directory "%~1" ^("%expanded%"^) not found
goto :endlocal
:showReg
<NUL set /P "=%~1: "
reg query HKCU\Environment /v Path 2>NUL|findstr /I "path"|findstr /V /R "^$"
if errorlevel 1 echo not defined
goto :eof
Provided examples show attempts to add
d:\FooBar
(rejected);d:\bat
(hard-coded reference);%SystemRoot%
(variable reference, hard-coded in the registry);^%windir^%
(variable reference keeps expandable in the registry).Output:
==>31602391.bat d:\FooBar
adding "d:\FooBar" to the user level HKCU\Environment /v Path
old: not defined
directory "d:\FooBar" ("d:\FooBar") not found
new: not defined
==>31602391.bat d:\test
adding "d:\test" to the user level HKCU\Environment /v Path
old: not defined
new: Path REG_EXPAND_SZ d:\test
==>31602391.bat %SystemRoot%
adding "C:\Windows" to the user level HKCU\Environment /v Path
old: Path REG_EXPAND_SZ d:\test
new: Path REG_EXPAND_SZ d:\test;C:\Windows
==>31602391.bat ^%windir^%
adding "%windir%" to the user level HKCU\Environment /v Path
old: Path REG_EXPAND_SZ d:\test;C:\Windows
new: Path REG_EXPAND_SZ d:\test;C:\Windows;%windir%
==>
setx path c:\whatever
For path
setx appends the path specified to the existing path. You don't specify the existing paths, only the new one. It also won't add a path twice.
Here's something I use
%windir%\system32\setx path %~sdp0 > "%temp%\filter.tmp"
The redirection hides error messages if I try and add twice. See the call /?
command if you don't know what %~sdp0
is
I found the answer here: https://superuser.com/questions/601015/how-to-update-the-path-user-environment-variable-from-command-line
@echo OFF
for /f "skip=2 tokens=3*" %%a in ('reg query HKCU\Environment /v PATH') do (
if [%%b]==[] (
setx PATH "%%~a;%cd%"
) else (
setx PATH "%%~a %%~b;%cd%"
)
)