windowsbatch-filecmdcallmethod-call

How do I call anotherfile.bat :label correctly in Batch?


I have a Batch file that's a library of functions like

:findmsbuild
if exist msbuildpath.txt (
    for /f %%i in (msbuildpath.txt) do set MSBUILD="%%i\MSBuild.exe"
) else (
    set VSWHERE="%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe"
    for /f "delims=" %%i in ('!VSWHERE! -latest -prerelease -products * -requires Microsoft.Component.MSBuild -find MSBuild\**\Bin\MSBuild.exe') do set MSBUILD="%%i"
)
exit /b

And the official documentation for call says that I should be able to call directly to a label in another file like

call library.bat :findmsbuild

but what happens instead is, the interpreter executes library.bat from the first line. What am I doing wrong? The calling Batch file is approximately

setlocal enableextensions enabledelayedexpansion
cd "%~dp0"
call library.bat :findmsbuild
echo %MSBUILD%

Solution

  • What are you doing wrong? Trusting Microsoft's documentation.

    You can either call externalbatch or call :internalroutine.

    To do what you want, you'd need to put a line like goto %1 at the start of your library file - and remember then that the parameter list has the label at the start, so you'd need to shift it, and %* would retain the label as the first parameter.