[windows] How do I add to the Windows PATH variable using setx? Having weird problems

I want to modify the Windows PATH variable using setx. The following works at least 50% of the time on Windows 8:

setx PATH %PATH%;C:\Python27\;C:\Python27\Scripts\

If it gives the error "the default argument can only be used 2 times", then the following works some of the time:

setx PATH "%PATH%;C:\Python27\;C:\Python27\Scripts\"

The difference is that we wrapped the second argument in quotes. I believe the quotes are necessary when %PATH% expands to include spaces.

However, I have encountered some weird problems on Windows 7. On one particular Windows 7 machine, I had this problem:

echo %PATH%

It prints:

C:\Foo\;C:\Bar\;[...lots of stuff...]C:\Baz\

Then I do this:

setx PATH "%PATH%;C:\Quux\"

Then it says "Error: Truncated at 1,024 characters." Now let's check what PATH contains:

echo %PATH%

It prints:

C:\Foo\;C:\Foo\;C:\Bar\;C:\Bar\;[...lots of stuff, now duplicated...]C:\B

...and it is cut off at 1,024 characters. It ran over because of the duplicates. Also interesting: The value of PATH changes despite the fact that setx raised an error and did not say "Success".

I was able to repeat this strange behavior several times (luckily I had saved the original contents of PATH).

At the moment, the only surefire way I know to append to the PATH is the following:

  1. echo the PATH.

  2. Copy the contents of PATH into a text file and manually add ;C:\Python27\;C:\Python27\Scripts\ to the end of the PATH.

  3. Copy the whole thing out of the text file.

  4. setx PATH "<paste the string here>"

That process works every single time on both Windows 7 and Windows 8.

I should really be able to do this in one command. What am I doing wrong?

Thank you.

This question is related to windows path cmd setx

The answer is


I was facing the same problems and found a easy solution now.

Using pathman.

pathman /as %M2%

Adds for example %M2% to the system path. Nothing more and nothing less. No more problems getting a mixture of user PATH and system PATH. No more hardly trying to get the correct values from registry...

Tried at Windows 10


Without admin rights the only way that worked for me is a bat file that contains the following code:

for /F "tokens=2* delims= " %%f IN ('reg query HKCU\Environment /v PATH ^| findstr /i path') do set OLD_SYSTEM_PATH=%%g
setx PATH "%USERPROFILE%\wev-tools;%OLD_SYSTEM_PATH%"

The code is the combination of the answers https://stackoverflow.com/a/45566845/4717152 and https://stackoverflow.com/a/10292113/4717152


I was having such trouble managing my computer labs when the %PATH% environment variable approached 1024 characters that I wrote a Powershell script to fix it.

You can download the code here: https://gallery.technet.microsoft.com/scriptcenter/Edit-and-shorten-PATH-37ef3189

You can also use it as a simple way to safely add, remove and parse PATH entries. Enjoy.


setx path "%PATH%; C:\Program Files (x86)\Microsoft Office\root\Office16" /m

This should do the appending to the System Environment Variable Path without any extras added, and keeping the original intact without any loss of data. I have used this command to correct the issue that McAfee's Web Control does to Microsoft's Outlook desktop client.

The quotations are used in the path value because command line sees spaces as a delimiter, and will attempt to execute next value in the command line. The quotations override this behavior and handles everything inside the quotations as a string.


If someone want to run it in PowerShell it works like below,

Run Powershell as Administrator

Then

setx /M PATH "$Env:PATH;<path to add>"

To verify, open another Powershell and view PATH as below,

$Env:PATH

Run cmd as administrator, then:

setx /M PATH "%PATH%;<your-new-path>"

The /M option sets the variable at SYSTEM scope. The default behaviour is to set it for the USER.

TL;DR

The truncation issue happens because when you echo %PATH% it will show the concatenation of SYSTEM and USER values. So when you add it in your second argument to setx, it will be fitting SYSTEM and USER values inside the USER var. When you echo again, things will be doubled.

Additionally, the /M option requires administrator privilege, so you need to open your terminal with "run as administrator", otherwise setx will complain with "access to registry path is denied".

Last thing to note: You won't see the new value when you echo %PATH% just after setting it this way, you need to close cmd and open again.

If you want to check the actual values stored in registry check this question.


If you're not beholden to setx, you can use an alternate command line tool like pathed. There's a more comprehensive list of alternative PATH editors at https://superuser.com/questions/297947/is-there-a-convenient-way-to-edit-path-in-windows-7/655712#655712

You can also edit the registry value directly, which is what setx does. More in this answer.

It's weird that your %PATH% is getting truncated at 1024 characters. I thought setx didn't have that problem. Though you should probably clean up the invalid path entries.


Steps: 1. Open a command prompt with administrator's rights.

Steps: 2. Run the command: setx /M PATH "path\to;%PATH%"

[Note: Be sure to alter the command so that path\to reflects the folder path from your root.]

Example : setx /M PATH "C:\Program Files;%PATH%"


Sadly with OOTB tools, you cannot append either the system path or user path directly/easily. If you want to stick with OOTB tools, you have to query either the SYSTEM or USER path, save that value as a variable, then appends your additions and save it using setx. The two examples below show how to retrieve either, save them, and append your additions. Don't get mess with %PATH%, it is a concatenation of USER+SYSTEM, and will cause a lot of duplication in the result. You have to split them as shown below...

Append to System PATH

for /f "usebackq tokens=2,*" %A in (`reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v PATH`) do set SYSPATH=%B

setx PATH "%SYSPATH%;C:\path1;C:\path2" /M

Append to User PATH

for /f "usebackq tokens=2,*" %A in (`reg query HKCU\Environment /v PATH`) do set userPATH=%B

setx PATH "%userPATH%;C:\path3;C:\path4"

This works perfectly:

for /f "usebackq tokens=2,*" %A in (`reg query HKCU\Environment /v PATH`) do set my_user_path=%B

setx PATH "C:\Python27;C:\Python27\Scripts;%my_user_path%"

The 1st command gets the USER environment variable 'PATH', into 'my_user_path' variable The 2nd line prepends the 'C:\Python27;C:\Python27\Scripts;' to the USER environment variable 'PATH'


This vbscript/batch hybrid "append_sys_path.vbs" is not intuitive but works perfectly:

If CreateObject("WScript.Shell").Run("%ComSpec% /C ""NET FILE""", 0, True) <> 0 Then
    CreateObject("Shell.Application").ShellExecute WScript.FullName, """" & WScript.ScriptFullName & """", , "runas", 5
    WScript.Quit
End If
Set Shell = CreateObject("WScript.Shell")
Cmd = Shell.Exec("%ComSpec% /C ""REG QUERY ""HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"" /v Path | FINDSTR /I /C:""REG_SZ"" /C:""REG_EXPAND_SZ""""").StdOut.ReadAll
Cmd = """" & Trim(Replace(Mid(Cmd, InStr(1, Cmd, "_SZ", VBTextCompare) + 3), vbCrLf, ""))
If Right(Cmd, 1) <> ";" Then Cmd = Cmd & ";"
Cmd = "%ComSpec% /C ""REG ADD ""HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"" /v Path /t REG_EXPAND_SZ /d " & Replace(Cmd & "%SystemDrive%\Python27;%SystemDrive%\Python27\Scripts"" /f""", "%", """%""")
Shell.Run Cmd, 0, True

Advantages of this approach:

1) It doesn't truncate the system path environment at 1024 characters.
2) It doesn't concatenate the system and user path environment.
3) It's automatically run as administrator.
4) Preserve the percentages in the system path environment.
5) Supports spaces, parentheses and special characters.
6) Works on Windows 7 and above.


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 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 cmd

'ls' is not recognized as an internal or external command, operable program or batch file '' is not recognized as an internal or external command, operable program or batch file XCOPY: Overwrite all without prompt in BATCH VSCode Change Default Terminal How to install pandas from pip on windows cmd? 'ls' in CMD on Windows is not recognized Command to run a .bat file VMware Workstation and Device/Credential Guard are not compatible How do I kill the process currently using a port on localhost in Windows? how to run python files in windows command prompt?

Examples related to setx

How do I add to the Windows PATH variable using setx? Having weird problems