Windows检查字符串包含另一个不起作用

时间:2016-08-01 09:42:14

标签: windows batch-file cmd

我有这个批处理文件附加一个环境变量(如果不存在)

setLocal EnableDelayedExpansion
set echo off                        

set envPath=%PATH%
set comPath=";D:\Package\Libraries\Lib"

if x%envPath:comPath=%==x%envPath% (
    setx PATH "%PATH%;D:\Package\Libraries\Lib" /M
)
pause

但它不起作用,并说这次文件出乎意料

我是根据Batch file: Find if substring is in string (not in a file)

撰写的

1 个答案:

答案 0 :(得分:2)

如上面的评论中所述,在主字符串中使用延迟扩展,在替换字符串中使用常规扩展。从快捷方式或从Admin Cmd Prompt:

运行此批处理为Admin
@echo off
setLocal EnableDelayedExpansion
set "comPath=D:\Package\Libraries\Lib"                     
set "envPath=%PATH%" & set "Separator="
if not "%envPath:~-1%" == ";" set "Separator=;"

if "!envPath:%comPath%=!"=="%envPath%" (
    setx PATH "%PATH%%Separator%%comPath%" /M )
timeout 5
exit /b

请注意,只有在Cmd重新启动时,才会从Registry重新读取更新的PATH。如果需要在同一批次中使用修改后的PATH,请使用SET而不是SETX为该Cmd会话临时设置PATH。

在类似的构造中,如果您的额外路径comPath在 IF或FOR循环中设置,请改用call set "PATH=%%envPath:!comPath!=%%"