I have this batch file to append a environment variable if not exists
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
But its not working and says file was unexpected this time
I wrote based on Batch file: Find if substring is in string (not in a file)
As mentioned in the above comment, use delayed expansion in the main string, and regular expansion in the replace string. Run this batch as Admin from shortcut or from Admin Cmd Prompt:
@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
Note that updated PATH will be re-read from Registry only upon Cmd restart. If you need to use the amended PATH in the same batch, use SET instead of SETX to set the PATH temporarily for that Cmd session.
In a similar construct, if your extra path comPath
is set inside IF or FOR loop, use call set "PATH=%%envPath:!comPath!=%%"
instead.