Adding a directory to the PATH environment variable in Windows

1,878,059

Solution 1

This only modifies the registry. An existing process won't use these values. A new process will do so if it is started after this change and doesn't inherit the old environment from its parent.

You didn't specify how you started the console session. The best way to ensure this is to exit the command shell and run it again. It should then inherit the updated PATH environment variable.

Solution 2

Option 1

After you change PATH with the GUI, close and re-open the console window.

This works because only programs started after the change will see the new PATH.

Option 2

This option only affects your current shell session, not the whole system. Execute this command in the command window you have open:

set PATH=%PATH%;C:\your\path\here\

This command appends C:\your\path\here\ to the current PATH. If your path includes spaces, you do NOT need to include quote marks.

Breaking it down:

  • set – A command that changes cmd's environment variables only for the current cmd session; other programs and the system are unaffected.
  • PATH= – Signifies that PATH is the environment variable to be temporarily changed.
  • %PATH%;C:\your\path\here\ – The %PATH% part expands to the current value of PATH, and ;C:\your\path\here\ is then concatenated to it. This becomes the new PATH.

Solution 3

WARNING: This solution may be destructive to your PATH, and the stability of your system. As a side effect, it will merge your user and system PATH, and truncate PATH to 1024 characters. The effect of this command is irreversible. Make a backup of PATH first. See the comments for more information.

Don't blindly copy-and-paste this. Use with caution.

You can permanently add a path to PATH with the setx command:

setx /M path "%path%;C:\your\path\here\"

Remove the /M flag if you want to set the user PATH instead of the system PATH.

Notes:

  • The setx command is only available in Windows 7 and later.
  • You should run this command from an elevated command prompt.

  • If you only want to change it for the current session, use set.

Solution 4

You don't need any set or setx command. Simply open the terminal and type:

PATH

This shows the current value of PATH variable. Now you want to add directory to it? Simply type:

PATH %PATH%;C:\xampp\php

If for any reason you want to clear the PATH variable (no paths at all or delete all paths in it), type:

PATH ;

Update

Like Danial Wilson noted in comment below, it sets the path only in the current session. To set the path permanently, use setx but be aware, although that sets the path permanently, but not in the current session, so you have to start a new command line to see the changes. More information is here.

To check if an environmental variable exist or see its value, use the ECHO command:

echo %YOUR_ENV_VARIABLE%

Solution 5

I would use PowerShell instead!

To add a directory to PATH using PowerShell, do the following:

$PATH = [Environment]::GetEnvironmentVariable("PATH")
$xampp_path = "C:\xampp\php"
[Environment]::SetEnvironmentVariable("PATH", "$PATH;$xampp_path")

To set the variable for all users, machine-wide, the last line should be like:

[Environment]::SetEnvironmentVariable("PATH", "$PATH;$xampp_path", "Machine")

In a PowerShell script, you might want to check for the presence of your C:\xampp\php before adding to PATH (in case it has been previously added). You can wrap it in an if conditional.

So putting it all together:

$PATH = [Environment]::GetEnvironmentVariable("PATH", "Machine")
$xampp_path = "C:\xampp\php"
if( $PATH -notlike "*"+$xampp_path+"*" ){
    [Environment]::SetEnvironmentVariable("PATH", "$PATH;$xampp_path", "Machine")
}

Better still, one could create a generic function. Just supply the directory you wish to add:

function AddTo-Path{
param(
    [string]$Dir
)

    if( !(Test-Path $Dir) ){
        Write-warning "Supplied directory was not found!"
        return
    }
    $PATH = [Environment]::GetEnvironmentVariable("PATH", "Machine")
    if( $PATH -notlike "*"+$Dir+"*" ){
        [Environment]::SetEnvironmentVariable("PATH", "$PATH;$Dir", "Machine")
    }
}

You could make things better by doing some polishing. For example, using Test-Path to confirm that your directory actually exists.

Share:
1,878,059
Netorica
Author by

Netorica

We provide affordable, fast, secure & reliable web hosting for Wordpress & PHP websites using top cloud providers with free migration, SSL, backups & security.

Updated on September 30, 2021

Comments

  • Netorica
    Netorica over 2 years

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

    I have already added it using the Environment Variables dialog box.

    But when I type into my console:

    C:\>path
    

    it doesn't show the new C:\xampp\php directory:

    PATH=D:\Program Files\Autodesk\Maya2008\bin;C:\Ruby192\bin;C:\WINDOWS\system32;C:\WINDOWS;
    C:\WINDOWS\System32\Wbem;C:\PROGRA~1\DISKEE~2\DISKEE~1\;c:\Program Files\Microsoft SQL
    Server\90\Tools\binn\;C:\Program Files\QuickTime\QTSystem\;D:\Program Files\TortoiseSVN\bin
    ;D:\Program Files\Bazaar;C:\Program Files\Android\android-sdk\tools;D:\Program Files\
    Microsoft Visual Studio\Common\Tools\WinNT;D:\Program Files\Microsoft Visual Studio\Common
    \MSDev98\Bin;D:\Program Files\Microsoft Visual Studio\Common\Tools;D:\Program Files\
    Microsoft Visual Studio\VC98\bin
    

    I have two questions:

    1. Why did this happen? Is there something I did wrong?
    2. Also, how do I add directories to my PATH variable using the console (and programmatically, with a batch file)?
    • George Stocker
      George Stocker about 10 years
      This is on topic because it's a question about 'tools programmers commonly use'. If you develop on Windows and you've never needed to modify the PATH, I'm surprised. To satiate the desire for being related to programming, I've highlighted what the highest voted answer pointed out: You can do this programmatically through the console (or via a batch file).
    • Netorica
      Netorica about 10 years
      thanks for the review @GeorgeStocker well yeah I did it programmatically and but I just haven't had an idea that I need to relogin after applying changes in the console session. (and I think its only in my case) but the highest voted answer generally answers the question
    • jww
      jww over 9 years
      @George - agreed, but as it stands, this question is written for Super User, and not Stack Overflow. Super User will provide help with web server configurations for personal use. Stack Overflow is for programming questions.
    • Tracker1
      Tracker1 over 7 years
      Exit and open a new console... If you're using bash, that may require a system reboot before the changes persist, depending on how/what you are using,.
    • Dave Jarvis
      Dave Jarvis about 3 years
  • JimR
    JimR almost 12 years
    @Ilya: I meant for you to open the console window after the path was changed in MyComputer->Properties->Advanced->Env Variables->Path. Some windows apps will propagate environment variable changes after they're started and some will not. WinXP cmd.exe does not.
  • user1703401
    user1703401 over 9 years
    Hmm, no, it truly really only modifies the registry. Ought to be a bit obvious from doing this in a Control Panel dialog instead of, say, the command prompt with the PATH command. You can observe what it does easily with SysInternals' Process Monitor, should you care. Using PATH is not the same, any changes you make will be lost when the console closes. SETX is a way to make persistent changes, like the dialog.
  • David 天宇 Wong
    David 天宇 Wong over 9 years
    if I exit the console and I rerun I have to reset the path. Any idea how to make this change permanent?
  • theB3RV
    theB3RV over 9 years
    @David天宇Wong If you follow "My Computer" > "Properties" > "Advanced" > "Environment Variables" > "Path". and add the directory to the end of that string, it will stay. Just be sure to open console after making the change.
  • David 天宇 Wong
    David 天宇 Wong over 9 years
    yup @theB3RV, it's just a long way to do something simple. It's weird that there is no persistant command that can be typed in the console
  • theB3RV
    theB3RV over 9 years
    @David天宇Wong Just found "SETX is a way to make persistent changes, like the dialog." so the SETX command should do it
  • Ilya Serbis
    Ilya Serbis almost 9 years
    SETX /M path "%path%;C:\Program Files (x86)\Git\bin\" to set PATH value on machine level
  • Peter Gordon
    Peter Gordon almost 9 years
    Why is this this not the accepted answer? I'd imagine most people would want to set their path permanently...
  • BrainSlugs83
    BrainSlugs83 almost 9 years
    This is correct. You always have to restart your console session before it picks up new environment variables.
  • BrainSlugs83
    BrainSlugs83 almost 9 years
    This is not persistent. As soon as you close your console window, your changes will be lost.
  • BrainSlugs83
    BrainSlugs83 almost 9 years
    @pgmann The accepted answer also permanent. The only one that's not is the crazy upvoted one using SET.
  • JimR
    JimR over 8 years
    @BrainSlugs83 I'm guessing either I wasn't clear enough or you didn't see the first half of the answer.
  • Dustin Woodard
    Dustin Woodard over 8 years
    It worked :) how about that! 'PATH %PATH%;' I can remember that
  • DavidPostill
    DavidPostill over 8 years
  • FF_Dev
    FF_Dev over 8 years
    WARNING : Because of the use of %PATH% variable, this command merge global env variables with users ones. Doesn't it ? This may creates unwanted side effects, especially with the /M switch
  • FF_Dev
    FF_Dev over 8 years
    WARNING 2: The %PATH% variable may not be in sync with environment variables as it is loaded at the launch of the command prompt and never reloaded afterward (even when executing setx command). Also it could have been changed locally by previously executed scripts.
  • Daniel Wilson
    Daniel Wilson over 8 years
    I think this only works for the instance of the cmd session, use setx to change it permanently
  • Paulo Matos
    Paulo Matos about 8 years
    My Powershell says %CD% is not recognized.
  • nclord
    nclord about 8 years
    @PauloMatos Could try using [System.Environment]::CurrentDirectory
  • John_West
    John_West almost 8 years
    Would the console session update the variables if WM_SETTINGCHANGE message was sent from an apllication? stackoverflow.com/a/8358361
  • user1703401
    user1703401 almost 8 years
    It is theoretically possible, no practical CRT implementation I know of actually does this. Explorer does.
  • Murali Murugesan
    Murali Murugesan almost 8 years
    What if path is already exists? It will be good to check for existance
  • overgroove
    overgroove over 7 years
    Didn't work for me. At least when using "set" instead of "setx". I needed to add an = between the variable name and value i.e. set path="..."
  • InsOp
    InsOp over 7 years
    for calling SetEnvironmentVariable with the Machine parameter you need to open the PowerShell with administrator rights
  • Tomasz Gandor
    Tomasz Gandor over 7 years
    This is an important difference between *nix-es and Windows. The batch runs in the same shell, and changes to the environment stay after it exits (at session scope). However, this cuts both ways: a batch file can obliterate your environment. (BTW, on *nix-es you'd just have to source such a file, like . mybatchfile).
  • Euro Micelli
    Euro Micelli over 7 years
    Background information corroborating this: blogs.msdn.microsoft.com/oldnewthing/20150915-00/?p=91591
  • icc97
    icc97 over 7 years
    Windows 10 has significantly improved the Path Environment variable editor now. Only took them 20 years to get round to it.
  • icc97
    icc97 over 7 years
    @overgroove That's because confusingly SET and SETX have similar but different syntaxes. SET PATH=... vs SETX PATH ...
  • J3STER
    J3STER over 7 years
    your answer seems to work only for the session, as soon as I exit and open a new command prompt, the path remains as it was at the start
  • icc97
    icc97 about 7 years
    Don't include quotes with this. For example call PATH %PATH%;C:\Program Files\... instead of PATH "%PATH%;C:\Program Files\..."
  • STWilson
    STWilson about 7 years
    Don't use setx! You risk truncation of your path variable, losing many other paths you spent time setting. Heed warnings above.
  • Balmipour
    Balmipour almost 7 years
    WARNING again : Since this method merges/truncates data, be sure to FIRST BACK-UP your %PATH% variable value. I know, this might seem obvious, but I'm not used to such destructive and permanent behaviours with such a little command by our days (Especially since I've been playing with path for years). While it just screwed my PATH, I'd like to be able to restore it, and... I'm not :). This answer deserves a much more clear WARNING, about the fact that this method will, at the same time add data, truncate data and be non-reversible.
  • abbood
    abbood almost 7 years
    it's bitterly disappointing that this "power" shell doesn't recognize %userprofile% nor $userprofile.. but then again, this is windows we're talking about
  • alexia
    alexia almost 7 years
    @abbood What you're looking for is $env:userprofile.
  • NET3
    NET3 over 6 years
    "Open the console window after you change the system path"... it's really helped out. thank you
  • David A. Gray
    David A. Gray almost 6 years
    Yes, it will, and I have implemented this feature a couple of times when I needed an environment variable to be both persisted in the Windows Registry and available for immediate use in the active session.
  • West Yang
    West Yang over 5 years
    @STWilson, too late to see your comment!
  • user6552940
    user6552940 over 5 years
    Hi @grzegorz-gajos, I was looking for exactly that, your link for more details gives 404. Any alternatives?
  • geneorama
    geneorama over 5 years
    Finally, I can get a true Linux experience in Windows. Reminds me of devrant.com/rants/618148/rant
  • Grzegorz Gajos
    Grzegorz Gajos over 5 years
    Sorry, the content from the link is no longer available. I removed.
  • René Nyffenegger
    René Nyffenegger about 5 years
    You should also specify either user or machine in the call of GetEnvironmentVariable. Otherwise, $PATH will contain the value of both the user and machine part of the registry which will unecessarily blow up the path variable when storing it again.
  • Farway
    Farway almost 5 years
    In a sense. What happens is that you start a new session within the current session. Leaving will require you call exit twice, first to close the new and then to close the first session (with the old environment).
  • basickarl
    basickarl over 4 years
    And how do you do this with a space in directory path.
  • Admin
    Admin over 4 years
    It looks like it worked but after i close the console and reopen, the path is not there and i can't find anything in the advanced system settings->environment->path
  • kaltu
    kaltu about 4 years
    It would be nicer if you add a note that Option 2 is session-wide, not system-wide.
  • Peter Mortensen
    Peter Mortensen almost 4 years
    Is there an explanation?
  • svinec
    svinec almost 4 years
    I don't know the technicality behind this, but Windows is just notorious with this, always restart first and only after that continue troubleshooting...
  • Aubrey Robertson
    Aubrey Robertson over 3 years
    This did nothing when I tried it. Are you missing an equal sign?
  • user2305193
    user2305193 over 3 years
    gtools can be easily installed using e.g. scoop with a oneliner: scoop install gtools in case this is useful for anyone else
  • lucidbrot
    lucidbrot about 3 years
    While Balmipour's warning is correct, at least it truncated it for me in such a way that the GUI now works again. This command solved to problem for me that no matter how many entries I deleted from the path, it still could not save it because it was too long.
  • Polv
    Polv over 2 years
    tl;dr it's best to use GUI. From start menu search.
  • Shidouuu
    Shidouuu over 2 years
    Please do not use this command under any circumstances, just use the GUI. My whole user path got overwritten after finding it on another website :(
  • rustyx
    rustyx about 2 years
    I just F***** UP my entire System PATH using that command. Bad, very bad.