[windows] Adding a directory to the PATH environment variable in Windows

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)?

This question is related to windows command-line path environment-variables

The answer is


If you run the command cmd, it will update all system variables for that command window.


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.


On Windows 10, I was able to search for set path environment variable and got these instructions:

  1. From the desktop, right-click the very bottom-left corner of the screen to get the Power User Task Menu.
  2. From the Power User Task Menu, click System.
  3. In the Settings window, scroll down to the Related settings section and click the System info link.
  4. In the System window, click the Advanced system settings link in the left navigation panel.
  5. In the System Properties window, click the Advanced tab, then click the Environment Variables button near the bottom of that tab.
  6. In the Environment Variables window (pictured below), highlight the Path variable in the System variables section and click the Edit button. Add or modify the path lines with the paths you want the computer to access. Each different directory is separated with a semicolon, as shown below:

C:\Program Files;C:\Winnt;C:\Winnt\System32

The first time I searched for it, it immediately popped up the System Properties Window. After that, I found the above instructions.


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.


  1. I have installed PHP that time. Extracted php-7***.zip into C:\php\
  2. Backup my current PATH environment variable: run cmd, and execute command: path >C:\path-backup.txt

  3. Get my current path value into C:\path.txt file (same way)

  4. Modify path.txt (sure, my path length is more than 1024 chars, windows is running few years)
    • I have removed duplicates paths in there, like 'C:\Windows; or C:\Windows\System32; or C:\Windows\System32\Wbem; - I've got twice.
    • Remove uninstalled programs paths as well. Example: C:\Program Files\NonExistSoftware;
    • This way, my path string length < 1024 :)))
    • at the end of path string add ;C:\php\
    • Copy path value only into buffer with framed double quotes! Example: "C:\Windows;****;C:\php\" No PATH= should be there!!!
  5. Open Windows PowerShell as Administrator.
  6. Run command:

setx path "Here you should insert string from buffer (new path value)"

  1. Re-run your terminal (I use "Far manager") and check: php -v

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

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.

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.

Regarding point 2 I'm using a simple batch file that is populating PATH or other environment variables for me. Therefore, there is no pollution of environment variables by default. This batch file is accessible from everywhere so I can type:

c:\>mybatchfile
-- here all env. are available
c:\>php file.php

As trivial as it may be, I had to restart Windows when faced with this problem.

I am running Windows 7 x64. I did a manual update to the system PATH variable. This worked okay if I ran cmd.exe from the stat menu. But if I type "cmd" in the Windows Explorer address bar, it seems to load the PATH from elsewhere, which doesn't have my manual changes.

(To avoid doubt - yes, I did close and rerun cmd a couple of times before I restarted and it didn't help.)


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


Use pathed from gtools.

It does things in an intuitive way. For example:

pathed /REMOVE "c:\my\folder"
pathed /APPEND "c:\my\folder"

It shows results without the need to spawn a new cmd!


  • Command line changes will not be permanent and will be lost when the console closes.
  • The path works like first comes first served.
  • You may want to override other already included executables. For instance, if you already have another version on your path and you want to add different version without making a permanent change on path, you should put the directory at the beginning of the command.

To override already included executables;

set PATH=C:\xampp\php;%PATH%;


In a command prompt you tell Cmd to use Windows Explorer's command line by prefacing it with start.

So start Yourbatchname.

Note you have to register as if its name is batchfile.exe.

Programs and documents can be added to the registry so typing their name without their path in the Start - Run dialog box or shortcut enables Windows to find them.

This is a generic reg file. Copy the lines below to a new Text Document and save it as anyname.reg. Edit it with your programs or documents.

In paths, use \\ to separate folder names in key paths as regedit uses a single \ to separate its key names. All reg files start with REGEDIT4. A semicolon turns a line into a comment. The @ symbol means to assign the value to the key rather than a named value.

The file doesn't have to exist. This can be used to set Word.exe to open Winword.exe.

Typing start batchfile will start iexplore.exe.

REGEDIT4
;The bolded name below is the name of the document or program, <filename>.<file extension>

[HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\App Paths\Batchfile.exe]

; The @ means the path to the file is assigned to the default value for the key.
; The whole path in enclosed in a quotation mark ".

@="\"C:\\Program Files\\Internet Explorer\\iexplore.exe\""

; Optional Parameters. The semicolon means don't process the line. Remove it if you want to put it in the registry

; Informs the shell that the program accepts URLs.

;"useURL"="1"

; Sets the path that a program will use as its' default directory. This is commented out.

;"Path"="C:\\Program Files\\Microsoft Office\\Office\\"

You've already been told about path in another answer. Also see doskey /? for cmd macros (they only work when typing).

You can run startup commands for CMD. From Windows Resource Kit Technical Reference

AutoRun

HKCU\Software\Microsoft\Command Processor

Data type Range Default value
REG_SZ  list of commands  There is no default value for this entry.

Description

Contains commands which are executed each time you start Cmd.exe.


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%

Aside from all the answers, if you want a nice GUI tool to edit your Windows environment variables you can use Rapid Environment Editor.

Try it! It's safe to use and is awesome!


A better alternative to Control Panel is to use this freeware program from SourceForge called Pathenator.

However, it only works for a system that has .NET 4.0 or greater such as Windows 7, Windows 8, or Windows 10.


Checking the above suggestions on Windows 10 LTSB, and with a glimpse on the "help" outlines (that can be viewed when typing 'command /?' on the cmd), brought me to the conclusion that the PATH command changes the system environment variable Path values only for the current session, but after reboot all the values reset to their default- just as they were prior to using the PATH command.

On the other hand using the SETX command with administrative privileges is way more powerful. It changes those values for good (or at least until the next time this command is used or until next time those values are manually GUI manipulated... ).

The best SETX syntax usage that worked for me:

SETX PATH "%PATH%;C:\path\to\where\the\command\resides"

where any equal sign '=' should be avoided, and don't you worry about spaces! There isn't any need to insert any more quotation marks for a path that contains spaces inside it - the split sign ';' does the job.

The PATH keyword that follows the SETX defines which set of values should be changed among the System Environment Variables possible values, and the %PATH% (the word PATH surrounded by the percent sign) inside the quotation marks, tells the OS to leave the existing PATH values as they are and add the following path (the one that follows the split sign ';') to the existing values.


Handy if you are already in the directory you want to add to PATH:

set PATH=%PATH%;%CD%

It works with the standard Windows cmd, but not in PowerShell.

For PowerShell, the %CD% equivalent is [System.Environment]::CurrentDirectory.


Examples related to windows

"Permission Denied" trying to run Python on Windows 10 A fatal error occurred while creating a TLS client credential. The internal error state is 10013 How to install OpenJDK 11 on Windows? I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? git clone: Authentication failed for <URL> How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning" XCOPY: Overwrite all without prompt in BATCH Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory how to open Jupyter notebook in chrome on windows Tensorflow import error: No module named 'tensorflow'

Examples related to command-line

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) Flutter command not found Angular - ng: command not found how to run python files in windows command prompt? How to run .NET Core console app from the command line Copy Paste in Bash on Ubuntu on Windows How to find which version of TensorFlow is installed in my system? How to install JQ on Mac by command-line? Python not working in the command line of git bash Run function in script from command line (Node JS)

Examples related to path

Get Path from another app (WhatsApp) How to serve up images in Angular2? How to create multiple output paths in Webpack config Setting the correct PATH for Eclipse How to change the Jupyter start-up folder Setting up enviromental variables in Windows 10 to use java and javac How do I edit $PATH (.bash_profile) on OSX? Can't find SDK folder inside Android studio path, and SDK manager not opening Get the directory from a file path in java (android) Graphviz's executables are not found (Python 3.4)

Examples related to environment-variables

Using Environment Variables with Vue.js Adding an .env file to React Project Is there any way to set environment variables in Visual Studio Code? Test process.env with Jest How to set environment variables in PyCharm? ARG or ENV, which one to use in this case? how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application? What is a good practice to check if an environmental variable exists or not? Passing bash variable to jq Tensorflow set CUDA_VISIBLE_DEVICES within jupyter