Adding a directory to the PATH environment variable in Windows

前端 未结 18 1344
我在风中等你
我在风中等你 2020-11-21 05:13

I am trying to add C:\\xampp\\php to my system PATH environment variable in Windows.

I have already added it using the Environment Varia

18条回答
  •  北荒
    北荒 (楼主)
    2020-11-21 06:07

    Safer SETX

    Nod to all the comments on the @Nafscript's initial SETX answer.

    • SETX by default will update your user path.
    • SETX ... /M will update your system path.
    • %PATH% contains the system path with the user path appended

    Warnings

    1. Backup your PATH - SETX will truncate your junk longer than 1024 characters
    2. Don't call SETX %PATH%;xxx - adds the system path into the user path
    3. Don't call SETX %PATH%;xxx /M - adds the user path into the system path
    4. Excessive batch file use can cause blindness1

    The ss64 SETX page has some very good examples. Importantly it points to where the registry keys are for SETX vs SETX /M

    User Variables:

    HKCU\Environment

    System Variables:

    HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

    Usage instructions

    Append to User PATH

    append_user_path.cmd

    @ECHO OFF
    REM usage: append_user_path "path"
    SET Key="HKCU\Environment"
    FOR /F "usebackq tokens=2*" %%A IN (`REG QUERY %Key% /v PATH`) DO Set CurrPath=%%B
    ECHO %CurrPath% > user_path_bak.txt
    SETX PATH "%CurrPath%";%1
    

    Append to System PATH

    append_system_path.cmd. Must be run as administrator.

    (It's basically the same except with a different Key and the SETX /M modifier.)

    @ECHO OFF
    REM usage: append_system_path "path"
    SET Key="HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
    FOR /F "usebackq tokens=2*" %%A IN (`REG QUERY %Key% /v PATH`) DO Set CurrPath=%%B
    ECHO %CurrPath% > system_path_bak.txt
    SETX PATH "%CurrPath%";%1 /M
    

    Alternatives

    Finally there's potentially an improved version called SETENV recommended by the ss64 SETX page that splits out setting the user or system environment variables.


    1. Not strictly true

提交回复
热议问题