Windows .bat/.cmd function library in own file?

后端 未结 6 2043
春和景丽
春和景丽 2021-02-05 14:50

there is a nice way to build functions in DOS .bat/.cmd script. To modularize some installation scripts, it would be nice to include a file with a library of functions into an .

6条回答
  •  终归单人心
    2021-02-05 15:41

    Another solution would be to temporary append the library functions to the running batch file.

    The original file can be saved in a temporary file before the change and restored when finished. This has the downside that you need to call the :deimport function at the end to restore the file and remove the temporary file. You also need to be able to write to the batch file and the folder you are currently in.

    demo.bat

    @ECHO OFF
    :: internal import call or external import call via wrapper function
    CALL:IMPORT test.bat "C:\path with spaces\lib 2.bat"
    :: external import call
    ::CALL importer.bat "%~f0%" test.bat "C:\path with spaces\lib 2.bat"
    
    CALL:TEST
    CALL:LIB2TEST
    
    CALL:DEIMPORT
    GOTO:EOF
    
    :: Internal version of the importer
    :IMPORT
    SETLOCAL
    IF NOT EXIST "%~f0.tmp" COPY /Y "%~f0" "%~f0.tmp">NUL
    SET "PARAMS=%*"
    SET "PARAMS=%PARAMS:.bat =.bat+%"
    SET "PARAMS=%PARAMS:.bat" =.bat"+%"
    COPY /Y "%~f0"+%PARAMS% "%~f0">NUL
    ENDLOCAL
    GOTO:EOF
    
    :: wrapper function for external version call
    :::IMPORT
    ::CALL import.bat "%~f0" %*
    ::GOTO:EOF
    
    :: Internal version of the deimporter
    :DEIMPORT
    IF EXIST "%~f0.tmp" (
      COPY /Y "%~f0.tmp" "%~f0">NUL
      DEL "%~f0.tmp">NUL
    )
    GOTO:EOF
    


    test.bat

    :test
    ECHO output from test.bat
    GOTO:EOF
    


    C:\path with spaces\lib 2.bat

    :LIB2TEST
    ECHO output from lib 2.bat
    GOTO:EOF
    


    Alternatively using the external version. Note this imports the deimport function so make sure you remove it in the demo.bat file.

    import.bat

    :: External version of the importer
    SETLOCAL EnableDelayedExpansion
    IF NOT EXIST "%~f1.tmp" COPY /Y "%~f1" "%~f1.tmp">NUL
    SET "PARAMS=%*"
    SET "PARAMS=!PARAMS:"%~f1" =!"
    SET "PARAMS=%PARAMS:.bat =.bat+%"
    SET "PARAMS=%PARAMS:.bat" =.bat"+%"
    COPY /Y "%~f1"+%PARAMS% "%~f1">NUL
    
    :: external version of the importer - remove the internal one before use!
    ECHO :DEIMPORT>>"%~f1"
    ECHO IF EXIST ^"%%~f0.tmp^" ^(>>"%~f1"
    ECHO.  COPY /Y ^"%%~f0.tmp^" ^"%%~f0^"^>NUL>>"%~f1"
    ECHO.  DEL ^"%%~f0.tmp^"^>NUL>>"%~f1"
    ECHO ^)>>"%~f1"
    ECHO GOTO:EOF>>"%~f1"
    ENDLOCAL
    GOTO:EOF
    

提交回复
热议问题