Adding a directory to the PATH environment variable in Windows - 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:
Why did this happen? Is there something I did wrong?
Also, how do I add directories to my PATH variable using the console (and programmatically, with a batch file)?

Option 1
After you change PATH with the GUI, close and reopen 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.

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.

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.

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%

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.

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
Backup your PATH - SETX will truncate your junk longer than 1024 characters
Don't call SETX %PATH%;xxx - adds the system path into the user path
Don't call SETX %PATH%;xxx /M - adds the user path into the system path
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.
Example
Here's a full example that works on Windows 7 to set the PATH environment variable system wide. The example detects if the software has already been added to the PATH before attempting to change the value. There are a number of minor technical differences from the examples given above:
#echo off
set OWNPATH=%~dp0
set PLATFORM=mswin
if defined ProgramFiles(x86) set PLATFORM=win64
if "%PROCESSOR_ARCHITECTURE%"=="AMD64" set PLATFORM=win64
if exist "%OWNPATH%tex\texmf-mswin\bin\context.exe" set PLATFORM=mswin
if exist "%OWNPATH%tex\texmf-win64\bin\context.exe" set PLATFORM=win64
rem Check if the PATH was updated previously
echo %PATH% | findstr "texmf-%PLATFORM%" > nul
rem Only update the PATH if not previously updated
if ERRORLEVEL 1 (
set Key="HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
for /F "USEBACKQ tokens=2*" %%A in (`reg query %%Key%% /v PATH`) do (
if not "%%~B" == "" (
rem Preserve the existing PATH
echo %%B > currpath.txt
rem Update the current session
set PATH=%PATH%;%OWNPATH%tex\texmf-%PLATFORM%\bin
rem Persist the PATH environment variable
setx PATH "%%B;%OWNPATH%tex\texmf-%PLATFORM%\bin" /M
)
)
)
1. Not strictly true

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.

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!

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%;

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!

Regarding point 2, I'm using a simple batch file that is populating PATH or other environment variables for me. Therefore, there isn’t any pollution of environment variables by default. This batch file is accessible from everywhere so I can type:
mybatchfile
Output:
-- Here all environment variables are available
And:
php file.php

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.

Use these commands in the Bash shell on Windows to append a new location to the PATH variable
PATH=$PATH:/path/to/mydir
Or prepend this location
PATH=/path/to/mydir:$PATH
In your case, for instance, do
PATH=$PATH:C:\xampp\php
You can echo $PATH to see the PATH variable in the shell.

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

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.

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.

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

The below solution worked perfectly.
Try the below command in your Windows terminal.
setx PATH "C:\myfolder;%PATH%"
SUCCESS: Specified value was saved.
You can refer to more on here.

I have installed PHP that time. I extracted php-7***.zip into C:\php</i>
Back up my current PATH environment variable: run cmd, and execute command: path >C:\path-backup.txt
Get my current path value into C:\path.txt file (the same way)
Modify path.txt (sure, my path length is more than 1024 characters, and 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 the 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!!!
Open Windows PowerShell as Administrator (e.g., Win + X).
Run command:
setx path "Here you should insert string from buffer (new path value)"
Rerun your terminal (I use "Far Manager") and check:
php -v

How to open the Environment Variables window from cmd.exe/Run... dialog
SystemPropertiesAdvanced and click "Environment Variables", no UAC
rundll32 sysdm.cpl,EditEnvironmentVariables direct, might trigger UAC
Via Can the environment variables tool in Windows be launched directly? on Server Fault.
How to open the Environment Variables window from Explorer
right-click on "This PC"
Click on "Properties"
On the left panel of the window that pops up, click on "Advanced System Settings"
Click on the "Advanced" tab
Click on "Environment Variables" button at the bottom of the window
You can also search for Variables in the Start menu search.
Reference images how the Environment Variables window looks like:
Windows 10
via
Windows 7
via
Windows XP
via

On Windows 10, I was able to search for set path environment variable and got these instructions:
From the desktop, right-click the very bottom-left corner of the screen to get the Power User Task Menu.
From the Power User Task Menu, click System.
In the Settings window, scroll down to the Related settings section and click the System info link.
In the System window, click the Advanced system settings link in the left navigation panel.
In the System Properties window, click the Advanced tab, then click the Environment Variables button near the bottom of that tab.
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.

Related

Looking for a better way to set up Windows environment variables from batch file after installing a software

I am building a Windows .bat script to automatically compile and install the Geant4 toolkit from CERN (but my following questions are independent of which of software I want to deal with). What I managed to do so far seems to work OK-ish, but I am not satisfied with how the environment variables are set at the end of the script.
To complete the installation, I have to set up environment variables to indicate the path to required data-sets, and C++ include and library directories (I choose to modify the "PATH" variable for these lasts). I want to set them up for the current script (using set command) and for the next executions (using setx command)
The script I am using now to do that is the following:
REM to get the path to directory where this bat file is executed from.
set G4_bat_file_dir=%~dp0
REM set the environement variables for next cmd runs
REM adding to local (temporary) PATH
set G4dataset_RootDir="%G4_bat_file_dir%\install\share\Geant4-10.4.3\data\"
REM adding environment variables for current and next cmd executions
setx G4dataset_RootDir "%G4_bat_file_dir%\install\share\Geant4-10.4.3\data\"
setx G4ABLADATA %G4dataset_RootDir%\G4ABLA3.1
setx G4ENSDFSTATEDATA %G4dataset_RootDir%\G4ENSDFSTATE2.2
setx G4LEDATA %G4dataset_RootDir%\G4EMLOW7.3
setx G4LEVELGAMMADATA %G4dataset_RootDir%\PhotonEvaporation5.2
setx G4NEUTRONHPDATA %G4dataset_RootDir%\G4NDL4.5
setx G4NEUTRONXSDATA %G4dataset_RootDir%\G4NEUTRONXS1.4
setx G4PIIDATA %G4dataset_RootDir%\G4PII1.3
setx G4RADIOACTIVEDATA %G4dataset_RootDir%\RadioactiveDecay5.2
setx G4REALSURFACEDATA %G4dataset_RootDir%\RealSurface2.1.1
setx G4SAIDXSDATA %G4dataset_RootDir%\G4SAIDDATA1.1
set G4ABLADATA=%G4dataset_RootDir%\G4ABLA3.1
set G4ENSDFSTATEDATA=%G4dataset_RootDir%\G4ENSDFSTATE2.2
set G4LEDATA=%G4dataset_RootDir%\G4EMLOW7.3
set G4LEVELGAMMADATA=%G4dataset_RootDir%\PhotonEvaporation5.2
set G4NEUTRONHPDATA=%G4dataset_RootDir%\G4NDL4.5
set G4NEUTRONXSDATA=%G4dataset_RootDir%\G4NEUTRONXS1.4
set G4PIIDATA=%G4dataset_RootDir%\G4PII1.3
set G4RADIOACTIVEDATA=%G4dataset_RootDir%\RadioactiveDecay5.2
set G4REALSURFACEDATA=%G4dataset_RootDir%\RealSurface2.1.1
set G4SAIDXSDATA=%G4dataset_RootDir%\G4SAIDDATA1.1
setx Geant4_DIR %G4_bat_file_dir%\install\lib\Geant4-10.4.3\
REM adding to PATH the paths to libraries and includes for Qt4 and Geant4.
setx PATH "%G4_bat_file_dir%\install\lib;%G4_bat_file_dir%\install\bin;%G4_bat_file_dir%\xerces-c\instal\bin;%G4_bat_file_dir%\xerces-c\instal\lib;%G4_bat_file_dir%Qt4\install\bin;%G4_bat_file_dir%Qt4\install\lib;%PATH%"
The paths %G4_bat_file_dir%\install\lib;%G4_bat_file_dir%\install\bin;%G4_bat_file_dir%\xerces-c\instal\bin;%G4_bat_file_dir%\xerces-c\instal\lib;%G4_bat_file_dir%Qt4\install\bin;%G4_bat_file_dir%Qt4\install\lib being the ones I want to append.
This is a screenshot of the environment variables set-up I get after running the script 2 times :
http://djienne.free.fr/env.png
This is far from ideal, there several things that I am not happy with:
all the paths in the variables get fully expended, and then also the PATH variable gets too long and I get the error "WARNING: The data being saved is truncated to 1024 characters."
If I run the script twice in a row, it produces duplicates in the PATH entries (and everything above the 1024 characters limit is truncated)
also, if I put this code at the end of my main compilation/installation script it gives the error 'setx' is not recognized as an internal or external command, operable program or batch file. and so the environment variables are not created/modified. But if I run this script as a separate .bat file, it works. So there is something I don't understand.
(I specify that I always do "run as administrator" to run the scripts.)
Thanks in advance for the help.
Following the advice from the comments, I built a batch script launch_visual_studio.bat at the top level of my project, to launch Visual Studio with an updated local PATH. The file contains the code:
#echo off
REM Set the environment
set G4_bat_file_dir=%~dp0
set QTDIR=%G4_bat_file_dir%Qt5\qt-5.6.3\
set QMAKESPEC=win32-msvc2015
set Geant4_DIR=%G4_bat_file_dir%install\lib\Geant4-10.4.3\
REM split into two parts for readability
set PATH=%PATH%;%G4_bat_file_dir%install\bin;%G4_bat_file_dir%install\lib;%G4_bat_file_dir%install\include\Geant4
set PATH=%PATH%;%QTDIR%lib;%QTDIR%bin;%QTDIR%include
REM launch visual studio
"%vs140comntools%..\IDE\devenv.exe"
This works for visual studio 2015, but will be different for other versions.
For the environment variables other than PATH, QTDIR and Geant4_DIR, since they have very specific names (G4ABLADATA, G4ENSDFSTATEDATA, ...), it seems fine to set them permanently using setx, as shown previously.

Unable to set PATH [duplicate]

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:
Why did this happen? Is there something I did wrong?
Also, how do I add directories to my PATH variable using the console (and programmatically, with a batch file)?
Option 1
After you change PATH with the GUI, close and reopen 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.
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.
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.
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%
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.
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
Backup your PATH - SETX will truncate your junk longer than 1024 characters
Don't call SETX %PATH%;xxx - adds the system path into the user path
Don't call SETX %PATH%;xxx /M - adds the user path into the system path
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.
Example
Here's a full example that works on Windows 7 to set the PATH environment variable system wide. The example detects if the software has already been added to the PATH before attempting to change the value. There are a number of minor technical differences from the examples given above:
#echo off
set OWNPATH=%~dp0
set PLATFORM=mswin
if defined ProgramFiles(x86) set PLATFORM=win64
if "%PROCESSOR_ARCHITECTURE%"=="AMD64" set PLATFORM=win64
if exist "%OWNPATH%tex\texmf-mswin\bin\context.exe" set PLATFORM=mswin
if exist "%OWNPATH%tex\texmf-win64\bin\context.exe" set PLATFORM=win64
rem Check if the PATH was updated previously
echo %PATH% | findstr "texmf-%PLATFORM%" > nul
rem Only update the PATH if not previously updated
if ERRORLEVEL 1 (
set Key="HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
for /F "USEBACKQ tokens=2*" %%A in (`reg query %%Key%% /v PATH`) do (
if not "%%~B" == "" (
rem Preserve the existing PATH
echo %%B > currpath.txt
rem Update the current session
set PATH=%PATH%;%OWNPATH%tex\texmf-%PLATFORM%\bin
rem Persist the PATH environment variable
setx PATH "%%B;%OWNPATH%tex\texmf-%PLATFORM%\bin" /M
)
)
)
1. Not strictly true
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.
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!
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%;
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!
Regarding point 2, I'm using a simple batch file that is populating PATH or other environment variables for me. Therefore, there isn’t any pollution of environment variables by default. This batch file is accessible from everywhere so I can type:
mybatchfile
Output:
-- Here all environment variables are available
And:
php file.php
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.
Use these commands in the Bash shell on Windows to append a new location to the PATH variable
PATH=$PATH:/path/to/mydir
Or prepend this location
PATH=/path/to/mydir:$PATH
In your case, for instance, do
PATH=$PATH:C:\xampp\php
You can echo $PATH to see the PATH variable in the shell.
If you run the command cmd, it will update all system variables for that command window.
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.
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.
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.)
The below solution worked perfectly.
Try the below command in your Windows terminal.
setx PATH "C:\myfolder;%PATH%"
SUCCESS: Specified value was saved.
You can refer to more on here.
I have installed PHP that time. I extracted php-7***.zip into C:\php</i>
Back up my current PATH environment variable: run cmd, and execute command: path >C:\path-backup.txt
Get my current path value into C:\path.txt file (the same way)
Modify path.txt (sure, my path length is more than 1024 characters, and 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 the 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!!!
Open Windows PowerShell as Administrator (e.g., Win + X).
Run command:
setx path "Here you should insert string from buffer (new path value)"
Rerun your terminal (I use "Far Manager") and check:
php -v
How to open the Environment Variables window from cmd.exe/Run... dialog
SystemPropertiesAdvanced and click "Environment Variables", no UAC
rundll32 sysdm.cpl,EditEnvironmentVariables direct, might trigger UAC
Via Can the environment variables tool in Windows be launched directly? on Server Fault.
How to open the Environment Variables window from Explorer
right-click on "This PC"
Click on "Properties"
On the left panel of the window that pops up, click on "Advanced System Settings"
Click on the "Advanced" tab
Click on "Environment Variables" button at the bottom of the window
You can also search for Variables in the Start menu search.
Reference images how the Environment Variables window looks like:
Windows 10
via
Windows 7
via
Windows XP
via
On Windows 10, I was able to search for set path environment variable and got these instructions:
From the desktop, right-click the very bottom-left corner of the screen to get the Power User Task Menu.
From the Power User Task Menu, click System.
In the Settings window, scroll down to the Related settings section and click the System info link.
In the System window, click the Advanced system settings link in the left navigation panel.
In the System Properties window, click the Advanced tab, then click the Environment Variables button near the bottom of that tab.
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.

adding a shell context menu item so that I can add folder to path by right clicking

Often at work I have to install new frameworks etc which do not add themselves to path and I have to go through the tedious process of adding the exectuables to path. I therefore decided to add a shell context menu item so that I can add any given folder to the path just by right clicking it and selecting "add to path".
I went through the normal routine of creating a context menu item and I used the following command to add the folder to path:
setx PATH "%PATH%;%1%"
This seems to not evaluate the PATH-variable, and instead replaces my PATH with something like this:
PATH;C:\Program Files (x86)\Android\android-sdk\platform-tools
Is there a way to make the context menu item evaluate %PATH% instead of just ignoring the percentage signs?
I've read about using \,^ and just adding an additional % but none of these approaches seem to work.
In case it matters, this is on a Windows 7 Enterprise computer
Managed to find a permanent solution.
Since setx sets the user path and not the system path, the command mentioned in my question will add all elements in the combined userpath + system path to PATH, effectively doubling its size every time you run the script.
This can either be fixed by removing user path, or as I did, add another user variable and append that to path. I then ended up with the following script afterwards to set the path correctly:
cmd /k setx UPATH "%%UPATH%%;%1%" && exit
This way I don't need to use a bat-file. Using double %s and &s seem to work as a way to escape the character, thus making it look like this to cmd:
setx UPATH "%UPATH%;drive:/theFolderYouRightClicked" & exit
I am still not sure why you have to pass this through cmd in order to see the PATH-variable, but at least this is a semi-clean way of solving my problem
Wowwwwww! I just spent the last 6+ hours of my life trying to be able to add a directory to my path (permanently) from the context menu. Well done Windows!
nircmd.exe elevate "cmd.exe" /k "setx /M PATH %%PATH%%;%1" && exit
Big thanks to #Metareven for some crucial bits (the double %s). Failed a few years back. Links below for related info and hopefully a reg file. AddToPath.reg
Wiped all my paths in the process! Totally worth it! :)
You need nircmd.exe in your C:\windows\system32 folder (or in your path!). The "/k" is necessary for god only knows why. "/M" is for machine, for system, for permanente. (I was like two attemps from giving up and wasting all these hours).
Use RapidEnvironmentEditor (in admin mode) to check, the cmd prompt that opens will not have the current PATH info. Get double ;s for some reason. Still doesn't work by reg file below (anyone know why??) You'll have to use regedit or AdvancedRegistryEditor to make an entry manually (see link below). Use EcMenu.exe to erase context menu mistakes (and other crud).
Windows Registry Editor Version 5.00 **doesn't work**
[HKEY_CLASSES_ROOT\Folder\shell\AddToPath]
"Add To Path"
[HKEY_CLASSES_ROOT\Folder\shell\AddToPath\command]
nircmd.exe elevate "cmd.exe" /k "setx /M PATH %%PATH%%;%1"
This did actually work for me (without the double %s) but only to User PATH:
cmd /k setx PATH "%PATH;"%1 && pause
How add context menu item to Windows Explorer for folders
How to Run a Program Elevated via the Right-Click Menu in Windows ...
This might also work instead of nircmd somehow: https://superuser.com/a/938121 "C:\Windows\System32\cmd.exe"="~ RUNASADMIN"
Tried this, didn't work: https://superuser.com/questions/266974/any-freeware-program-for-adding-editing-path-from-context-menu

How to update system PATH variable permanently from cmd?

We can use setx as discussed here.
setx PATH "%PATH%;C:\Something\bin"
But this command can just make changed to user PATH variable not the system one.
How can we make a similar system wide command?
Type setx /? to get basic command help. You'll easily discover:
/M Specifies that the variable should be set in
the system wide (HKEY_LOCAL_MACHINE)
environment. The default is to set the
variable under the HKEY_CURRENT_USER
environment.
You need to run this from an elevated command prompt. Right-click the cmd shortcut and select Run as Administrator.
E.g.
setx /M PATH "%PATH%;C:\Something\bin"
Caution:
We may destroy the current system's PATH variable. Make sure you backup its value before you modify it.
From powershell
setx /M PATH "$($env:path);c:\program files\mynewprogram"
Solution when dealing with a >1024 char path:
None of the other answers worked in my case, but using pathed did the trick. You can append to path as simply as this:
pathed /append C:\Path\To\Be\Added /machine
You can check if the edit happened correctly by running
pathed
PS: if you want to change the user's path instead use:
pathed /append C:\Path\To\Be\Added /user
and pathed /user to check if it went through correctly.
PPS: In order to be able to run pathed from terminal, you need to put the exe in a directory already on your path (or add a new directory to path, but then you you might need to open a new instance of cmd.exe in order for the new path to be recognized)
One problem with %PATH%, is it includes the user's path. If you don't mind Powershell, you can run the following
$p = [Environment]::GetEnvironmentVariable("PATH", [EnvironmentVariableTarget]::Machine);
[Environment]::SetEnvironmentVariable("PATH", $p + ";C:\MyPath", [EnvironmentVariableTarget]::Machine);
If you want to add some location to the PATH environment variable on user level, use the following on the command line:
setx PATH ^%PATH^%;"C:\Program Files\Something\bin"
Why the strange syntax?
First, you do not want to expand the system PATH variable but keep it as a symbol, otherwise you will not participate in future additions to the system PATH variable. Therefore, you have to quote the % characters with ^.
If you use this in a command script, you have to use double %% instead of ^%.
The " encloses a string that contains spaces. If you do not have spaces, you can omit the quotes.
The added string has to follow directly without space so the whole thing forms a single argument to the setx command.
Please refer to Adding a directory to the PATH environment variable in Windows
append_user_path.cmd
append_system_path.cmd
- both work just fine

Windows batch, select ONLY user variables

In environment variables I have a PATH variable for both user variables and system variables.
In a batch script, in order for me to append the user PATH variable with a new given path, I need to select the current value. Unfortunately %PATH% returns a combination of the user variable and the system variable.
Of course I only want to add a new custom path value to the user variable. There is no point in enhancing it with the system path as well. That's why I have 2 variables.
Thanks in advance.
Edit: Found in the documentation the following statement:
The %PATH% variable is set as both a system and user variable, the 2 values are combined to give the PATH for the currently logged in user....
Example:
User variables:
PATH
value: c:\dev
System variables
PATH
value: c:\Program Files
What I want to do, is to add to the user variable the value: c:\tmp, so that in the end PATH will have the value: c:\dev;c:\tmp
But, if open a cmd window:
echo %PATH%
c:\Program Files;c:\dev
so the setx will do the following
setx path "%path%;c:\tmp"
open new cmd
echo %PATH%
c:\Program Files;c:\dev;c:\tmp
And that is wrong, because I only needed c:\dev;c:\tmp
I hope I was more clear this time.
How are you modifying the variables?
There is only one environment variable PATH, so you can go ahead and change it. These changes are transient (and local to your process and its children).
There are two (actually more) persistent places in Registry from which the environment variables are initialized when a process is created. You can modify them using reg utility. There is no ambiguity since they are separate:
HKEY_CURRENT_USER\Environment
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
You may have to re-login for changes in Registry to take effect (I don't remember whether there's a programmatic way to notify explorer that these settings have changed). Also note that by default child processes inherit the environment of their parent (unless the parent takes special measures to do otherwise), so e.g. if you launch a cmd window and later modify the environment via system settings dialog, applications started from that cmd won't see the changes.
[UPD] You can get the value of user-specific environment variable from registry using reg utility:
reg query HKCU\Environment /v PATH
Though you'll have to filter its output for the actual value, as it spits out some useless text. Here an example incantation:
for /f "usebackq tokens=2,*" %A in (`reg query HKCU\Environment /v PATH`) do set value=%B
It will store the result in the environment variable value. Remember to double %'s when using it in a batch file.
If I understand your question, you have 2 %PATH% variables. One system one, and one user one, (presumably you created the latter yourself).
I have tried this and it seems to work for user environment variables
setx /s computername PATH %PATH%;newpathvalue
When I tested this I actually substituted PATH for a new var to make sure it works, but it may be best making a copy of your existing vars before doing this, just in case.
It will tag onto the end of the existing user environment variable PATH with the new value you specify, separating it from the others with a semi-colon ;.
Hope this helps

Resources