matthias_buehlmann
matthias_buehlmann

Reputation: 5091

Robust path to visual studio's vcvars64.bat

VisualStudio has vcvars64.bat that loads all necessary environment variables to compile visual studio projects from the command line.

In VisualStudio 2017 community edition, this file for example resides in

C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars64.bat

How can I construct the path to this file in a batch script, only using system set environment variables, independently of which visual studio version is installed?

Upvotes: 2

Views: 2163

Answers (1)

jessehouwing
jessehouwing

Reputation: 115017

You can use vswhere to detect the install location of Visual Studio related files. This snippet from the wiki comes pretty close to what you need:

for /f "usebackq delims=" %%i in (`vswhere.exe -prerelease -latest -property installationPath`) do (
  if exist "%%i\Common7\Tools\vsdevcmd.bat" (
    %comspec% /k "%%i\Common7\Tools\vsdevcmd.bat" %*
    exit /b
  )
)

rem Instance or command prompt not found
exit /b 2

Changing that snippet to call vcvars should be easy.

If you have multiple Visual Studio installations that may not have the C++ workload installed, you can search for an instance with a specific workload or component, like this one looking for Team Explorer to be part of the installation:

vswhere -latest -products * -requires Microsoft.VisualStudio.TeamExplorer -property installationPath

The Microsoft C++ team wrote a blog about vswhere and alternative options. They also list all of the relevant workload and component identifiers.

The idea is that you ship vswhere.exe with your scripts or executable. Or downlead it on demand. I use this powershell snippet in a few places to grab vswhere when I need it:

$vswhereLatest = "https://github.com/Microsoft/vswhere/releases/latest/download/vswhere.exe"
$vswherePath = ".\vswhere.exe"
remove-item $vswherePath
invoke-webrequest $vswhereLatest -OutFile $vswherePath

The reason behind this, is that you can now install multiple instances of the same Visual Studio Version. Each stores its settings in a private registry file. There is no easy way to get to the InstallPath registry key that used to exist. More background can be found here. Complete with a few reg.exe commands to load the private registry hyves and query them. It you really can't package or fetch vswhere on demand, this may be your only option (add 16.*to include 2019)

for /d %%f in (%LOCALAPPDATA%\Microsoft\VisualStudio\15.0_*) do reg load HKLM\_TMPVS_%%~nxf "%%f\privateregistry.bin"

REM Use `reg query` to grab the InstallPath from the instance

for /d %%f in (%LOCALAPPDATA%\Microsoft\VisualStudio\15.0_*) do reg unload HKLM\_TMPVS_%%~nxf

Note: Looks like this may need to be updated to search for 15.*_* and 16.*_* to detect point releases as well as Visual Studio 2019.

Upvotes: 2

Related Questions