Context: I need to call a Windows batch script which would update my PATH by adding another path \'xxx\' at the end of it, but:
The page "DOS - Function Collection" gives great example on how a function can return a value in DOS, even when using delayed expansion mode:
The following function will update any variable you want with an addition PATH:
:cleanAddPath -- remove %~2 from %~1, add it at the end of %~1
SETLOCAL ENABLEDELAYEDEXPANSION
set P=!%~1!
set P=!P:%~2=!
set P=!P:;;=;!
set P=!P!;%~2
set P=!P:;;=;!
(ENDLOCAL & REM.-- RETURN VALUES
SET "%~1=%P%"
)
exit /b
Note the concatenation of paths using. As jeb comments:
The line
set P=%P%;%~2is critical if your path contains ampersands like inC:\Documents&Settings.
Better change to set "P=!P!;%~2".
The SET "%~1=%P%" is the part which allows to memorize (in the variable represented by %~1) the value you have set using delayed expansion features.
I initially used SET "%~1=%P%" !, but jeb comments:
The command
SET "%~1=%P%" !could be simplified toSET "%~1=%P%"as the trailing exclamation mark has only a (good) effect in delayed expansion mode and if you prepared%P%before.
To update your PATH variable, you would call your function with:
call :cleanAddPath PATH "C:\my\path\to\add"
And it will persists after leaving that script, for your current DOS session.
dbenham's answer points to a more robust answer (upvoted), but in my case this script is enough.