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

后端 未结 3 1616
悲&欢浪女
悲&欢浪女 2020-12-10 04:39

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:

3条回答
  •  爱一瞬间的悲伤
    2020-12-10 05:31

    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%;%~2 is critical if your path contains ampersands like in C:\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 to SET "%~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.

提交回复
热议问题