已编辑 - 调整评论中的更正(没有jeb,没有防弹,只是尽量不要射你的脚)
只是为了完成,此批次仅在尚未包含的情况下将一个或多个元素添加到指示的变量
@echo off
call :addToVariable %*
exit /b
:addToVariable
rem %1 = variable name where to add elements
rem %2 = element to add
rem %3-... the rest of the elements. Will be shifted to retrieve
rem if no data, no work
if "%~1"=="" goto :EOF
if "%~2"=="" goto :EOF
rem prepare environment to work
setlocal enableextensions enabledelayedexpansion
rem get variable name to work
set "_var=%~1"
rem get original value of variable
if defined %_var% (
set "_value=!%_var%:"=!"
rem " this line does nothing but correct sintax highlighting
) else (
set _value=
)
rem skip to arguments with elements to include
shift
rem list of elements to add to original variable
set _add=
:addToVariableLoop
rem iterate over parameters
for %%d in ( %1 ) do (
rem test if new directory already in original or temporary variable
echo ";!_value!;!_add!;" | findstr /i /c:";%%~d;" >nul 2>nul
rem if not in variable, add to temporary variable
if not errorlevel 1 (
echo [%%~d] already included
) else (
echo adding [%%~d]
set "_add=!_add!;%%~d"
)
)
rem check if more elements are pending in call
if not "%~2"=="" (
shift
goto :addToVariableLoop
)
set "_value=%_value%%_add%"
endlocal & set "%_var%=%_value%"
goto :EOF
如果批处理文件是pathAdd.cmd
,添加到路径变量调用为
pathAdd path c:\windows;c:\test;"c:\something more"
添加到 classPath 变量调用为
pathAdd classPath c:\windows\system32\drivers
添加到 PSModulePath 变量调用为
pathAdd PSModulePath "c:\Somewhere over the rainbow";c:\Users
……