visual studio 的稳健路径 vcvars64.bat

Robust path to visual studio's vcvars64.bat

VisualStudio vcvars64.bat 加载所有必要的环境变量以从命令行编译 visual studio 个项目。

在 VisualStudio 2017 社区版中,例如此文件驻留在

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

如何在批处理脚本中构造此文件的路径,仅使用系统设置环境变量,独立于安装的 visual studio 版本?

您可以使用vswhere检测Visual Studio相关文件的安装位置。 wiki 中的这段代码非常接近您的需要:

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

更改该片段以调用 vcvars 应该很容易。

如果您有多个 Visual Studio 安装可能没有安装 C++ 工作负载,您可以搜索具有特定工作负载或组件的实例,例如这个寻找 Team Explorer 作为安装一部分的实例:

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

Microsoft C++ 团队编写了 a blog about vswhere and alternative options。他们还列出了所有相关的工作负载和组件标识符。

我们的想法是 vswhere.exe 随脚本或可执行文件一起发布。或者按需下载。我在几个地方使用这个 powershell 片段来在我需要的时候抓取 vswhere:

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

这背后的原因是,您现在可以安装同一 Visual Studio 版本的多个实例。每个都将其设置存储在私有注册表文件中。没有简单的方法可以访问曾经存在的 InstallPath 注册表项。 More background can be found here。完成一些 reg.exe 命令以加载私有注册表 hyves 并查询它们。如果您真的无法按需打包或获取 vswhere,这可能是您唯一的选择(添加 16.* 以包括 2019)

for /d %%f in (%LOCALAPPDATA%\Microsoft\VisualStudio.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.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.