如何使用 setx 添加到 Windows PATH 变量?遇到奇怪的问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19287379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 10:58:32  来源:igfitidea点击:

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

windowspathcmdsetx

提问by SerMetAla

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

我想使用setx. 以下在 Windows 8 上至少有 50% 的时间有效:

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:

如果它给出错误“默认参数只能使用 2 次”,那么以下内容有时会起作用:

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.

不同之处在于我们将第二个参数用引号括起来。我相信当%PATH%扩展为包含空格时,引号是必要的。

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

但是,我在 Windows 7 上遇到了一些奇怪的问题。在一台特定的 Windows 7 机器上,我遇到了这个问题:

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:

然后它说“错误:截断为 1,024 个字符。” 现在让我们检查一下 PATH 包含什么:

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 setxraised an error and did not say "Success".

...它被截断为 1,024 个字符。它因为重复而跑了。同样有趣的是: PATH 的值发生了变化,尽管setx引发了错误并且没有说“成功”。

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

我能够多次重复这种奇怪的行为(幸运的是我保存了 PATH 的原始内容)。

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

目前,我知道附加到 PATH 的唯一可靠方法如下:

  1. echothe 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>"

  1. echo路径。

  2. 将 PATH 的内容复制到文本文件中并手动添加;C:\Python27\;C:\Python27\Scripts\到 PATH 的末尾。

  3. 从文本文件中复制整个内容。

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

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

该过程在 Windows 7 和 Windows 8 上每次都有效。

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

我真的应该能够在一个命令中做到这一点。我究竟做错了什么?

Thank you.

谢谢你。

回答by Vituel

Run cmdas administrator, then:

cmd以管理员身份运行,然后:

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.

/M 选项在 SYSTEM 范围内设置变量。默认行为是为 USER 设置它。

TL;DR

TL; 博士

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.

发生截断问题是因为当您回显 %PATH% 时,它将显示 SYSTEM 和 USER 值的串联。因此,当您将它添加到 setx 的第二个参数中时,它将在 USER 变量中拟合 SYSTEM 和 USER 值。当你再次回声时,事情就会翻倍。

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

此外,/M 选项需要管理员权限,因此您需要使用“以管理员身份运行”打开终端,否则 setx 会抱怨“访问注册表路径被拒绝”。

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 cmdand open again.

最后要注意的是:这样设置后,当您回显 %PATH% 时您将看不到新值,您需要关闭cmd并再次打开。

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

如果要检查存储在注册表中的实际值,请检查此问题

回答by Manohar Reddy Poreddy

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'

第一个命令将 USER 环境变量 'PATH' 放入 'my_user_path' 变量中 第二行在 'C:\Python27;C:\Python27\Scripts;' 前面 到用户环境变量“PATH”

回答by NIK

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

如果有人想在 PowerShell 中运行它,它的工作方式如下,

Run Powershell as Administrator

以管理员身份运行 Powershell

Then

然后

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

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

要验证,请打开另一个 Powershell 并查看 PATH,如下所示,

$Env:PATH

回答by Andreas M. Oberheim

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

没有管理员权限,对我有用的唯一方法是包含以下代码的 bat 文件:

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/4717152and https://stackoverflow.com/a/10292113/4717152

代码是答案的组合https://stackoverflow.com/a/45566845/4717152https://stackoverflow.com/a/10292113/4717152

回答by Ehtesh Choudhury

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

如果您不setx喜欢 ,则可以使用替代命令行工具,例如pathed。在https://superuser.com/questions/297947/is-there-a-convenient-way-to-edit-path-in-windows-7/655712#655712 中有更全面的替代 PATH 编辑器列表

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

您也可以直接编辑注册表值,这就是这样setx做的。在这个答案中更多。

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

奇怪的%PATH%是,您的1024 个字符被截断了。我以为setx没有这个问题。尽管您可能应该清理无效的路径条目。

回答by Markus

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

例如将 %M2% 添加到系统路径。不多也不少。混合使用用户 PATH 和系统 PATH 不再有问题。不再试图从注册表中获取正确的值...

Tried at Windows 10

在 Windows 10 上试过

回答by Raj Tukadiya

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

步骤: 1.以管理员权限打开命令提示符。

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

步骤: 2.运行命令:setx /M PATH "path\to;%PATH%"

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

[注意:请务必更改命令,以便 path\to 反映从您的根目录开始的文件夹路径。]

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

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

回答by Inetquestion

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

遗憾的是,使用 OOTB 工具,您无法直接/轻松地附加系统路径或用户路径。如果您想坚持使用 OOTB 工具,您必须查询 SYSTEM 或 USER 路径,将该值保存为变量,然后附加您的添加并使用 setx 保存它。下面的两个示例显示了如何检索、保存和附加您的添加内容。不要弄乱 %PATH%,它是 USER+SYSTEM 的串联,并且会导致结果中有很多重复。您必须将它们分开,如下所示...

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"

回答by Riccardo La Marca

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

这个 vbscript/batch 混合“append_sys_path.vbs”并不直观,但效果很好:

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.

1) 它不会在 1024 个字符处截断系统路径环境。
2)它不连接系统和用户路径环境。
3)它自动以管理员身份运行。
4) 保留系统路径环境中的百分比。
5) 支持空格、括号和特殊字符。
6) 适用于 Windows 7 及更高版本。

回答by Carl Bennett

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.

当 %PATH% 环境变量接近 1024 个字符时,我在管理我的计算机实验室时遇到了这样的麻烦,我编写了一个 Powershell 脚本来修复它。

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

您可以在此处下载代码: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.

您还可以将其用作安全添加、删除和解析 PATH 条目的简单方法。享受。