How to keep the value of a variable outside a Windows batch script which uses "delayed expansion local" mode?

Viewed 6223

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:

  • without any duplicate
    (if I add 'xxx' to a PATH like 'aaa;xxx;bbb', I need an updated PATH like 'aaa;bbb;xxx')
  • without any aggregation
    (I can call the script repeatedly without ending up with 'aaa;bbb;xxx;xxx;xxx;...')

What I have tried:

The following function takes care of any duplicate and does the job

:cleanAddPath -- remove %~1 from PATH, add it at the end of PATH
SETLOCAL ENABLEDELAYEDEXPANSION
set PATH=!PATH:%~2=!
set PATH=!PATH:;;=;!
set PATH=%PATH%;%~2
set P=!P:;;=;!
echo %PATH%
echo -------------
ENDLOCAL  
exit /b

But, it needs delayed expansion local mode, which means: at the end of the script (or here, at the end of the function cleanAddPath), whatever has been set for %PATH% is thrown away.

I could ask the users (for which I write the script) to launch their cmd with a cmd /V:ON option (activating the delayed expansion, otherwise off by default), but that is not practical.

How can I modify the PATH variable the way I described above, and still have it updated in my current DOS session after calling said script?

3 Answers
Related