echo %PATH%
如果您的(机器级别)%path%
以尾随\
反向固线(反斜杠)结尾,则应将其加倍,如下所示:
if "%path:~-1%"=="\" (
SETX PATH "%PATH%\"
) else (
SETX PATH "%PATH%"
)
资源:语法:转义字符、分隔符和引号(请注意以下引文中我自己的亮点):
某些命令(例如REG
和FINDSTR
)使用标准转义字符 of \
(如 C、Python、SQL、bash 和许多其他语言所使用的那样)。\
转义可能会导致包含尾随反斜杠的引用目录路径出现问题,因为末尾的右"
引号的行会被转义\"
。
要保存带有尾部反斜杠 ( \
) 的目录路径,需要添加第二个反斜杠以“转义转义”,例如,而不是
"C:\My Docs\"
使用"C:\My Docs\\"
上述关于尾随的陈述\
也适用于 SETX
。这是一个例子:
==>set myPath
myPath=D:\Program Files\OgreSDK\
==>setx myOgre "%myPath%"
SUCCESS: Specified value was saved.
==>reg query HKEY_CURRENT_USER\Environment /v myOgre
HKEY_CURRENT_USER\Environment
myOgre REG_SZ D:\Program Files\OgreSDK"
==>setx myOgre "%myPath%\"
SUCCESS: Specified value was saved.
==>reg query HKEY_CURRENT_USER\Environment /v myOgre
HKEY_CURRENT_USER\Environment
myOgre REG_SZ D:\Program Files\OgreSDK\
==>
该错误与第一次使用用户级别环境变量导致的Invalid syntax
用户级别变量损坏有关,该用户级别环境变量优先于机器级别一。要解决此问题,请先通过 Windows GUI(首选)调整用户级别变量(或完全删除它) :%PATH%
SETX PATH "%PATH%"
%PATH%
Control Panel | System | Advanced | Environment Variables
证明 -分两步重现问题:
步骤#1:从%myPath%
机器级别的良好变量开始,尾随\
; 最后(很好)打破了当前用户级别和会话exit
的这个变量。cmd
==>set myPath
myPath=D:\temp\foo foo\
==>reg query HKEY_CURRENT_USER\Environment /v myPath
ERROR: The system was unable to find the specified registry key or value.
==>reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v myPath
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
myPath REG_SZ D:\temp\foo foo\
==>setx myPath "%myPath%;D:\temp\bu bu bu"
SUCCESS: Specified value was saved.
==>reg query HKEY_CURRENT_USER\Environment /v myPath
HKEY_CURRENT_USER\Environment
myPath REG_SZ D:\temp\foo foo\;D:\temp\bu bu bu
==>rem fetch erroneous state
==>setx myPath "%myPath%"
SUCCESS: Specified value was saved.
==>reg query HKEY_CURRENT_USER\Environment /v myPath
HKEY_CURRENT_USER\Environment
myPath REG_SZ D:\temp\foo foo"
==>exit
步骤#2:在一个新cmd
会话中,从用户级别的损坏%myPath%
变量开始,尾随"
; 这会引发所描述的错误。
==>set myPath
myPath=D:\temp\foo foo"
==>reg query HKEY_CURRENT_USER\Environment /v myPath
HKEY_CURRENT_USER\Environment
myPath REG_SZ D:\temp\foo foo"
==>reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v myPath
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
myPath REG_SZ D:\temp\foo foo\
==>setx myPath "%myPath%;D:\temp\bu bu bu"
ERROR: Invalid syntax. Default option is not allowed more than '2' time(s).
Type "SETX /?" for usage.
==>reg query HKEY_CURRENT_USER\Environment /v myPath
HKEY_CURRENT_USER\Environment
myPath REG_SZ D:\temp\foo foo"
==>