Append a directory to PATH Environment Variable in Windows

后端 未结 3 1832
感情败类
感情败类 2021-01-24 09:47

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

3条回答
  •  一整个雨季
    2021-01-24 10:14

    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|findstr /I "path"|findstr /V /R "^$"
    if errorlevel 1 echo not defined
    goto :eof
    

    Provided examples show attempts to add

    • a non existent directory d:\FooBar (rejected);
    • an existent directory d:\bat (hard-coded reference);
    • an existent directory %SystemRoot% (variable reference, hard-coded in the registry);
    • an existent directory ^%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%
    
    ==>
    

提交回复
热议问题