Skip to content

Find MSBuild

Heath Stewart edited this page Jan 5, 2019 · 11 revisions

Find MSBuild

MSBuild is an optional component for Visual Studio and also installed with Build Tools. By default, vswhere will look for Community, Professional, and Enterprise editions of Visual Studio but you can optionally pass a list of products to search.

The following examples use the latest release. For examples that work with older releases, please view the history of this page.

With Visual Studio 2017 Update 2 or newer installed, you can find vswhere at %ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe, or to make sure it's always available in your repo see Installing for an option using NuGet.

Starting in Visual Studio 2019 Preview, MSBuild will use "Current" instead of the major version number to make it easier to invoke for different versions. This is reflected in the examples below that fall back to "15.0" to support Visual Studio 2017 and Build Tools for Visual Studio 2017.

Batch

Note below that the examples are written as if in a batch script, which requires escaping "%" with another "%" which is why you see "%%i". If you were typing this in the command prompt you would use only one "%" like "%i".

@echo off
setlocal enabledelayedexpansion

for /f "usebackq tokens=*" %%i in (`vswhere -latest -prerelease -products * -requires Microsoft.Component.MSBuild -property installationPath`) do (
  set InstallDir=%%i
)

set tool="!InstallDir!\MSBuild\Current\Bin\MSBuild.exe"
if not exist !tool! (
  set tool="!InstallDir!\MSBuild\15.0\Bin\MSBuild.exe"
  if not exist !tool! exit /b 2
)

!tool! %*

PowerShell

The following examples are equivalent to those above but written for PowerShell.

$path = vswhere -latest -prerelease -products * -requires Microsoft.Component.MSBuild -property installationPath
if ($path) {
  $tool = join-path $path 'MSBuild\Current\Bin\MSBuild.exe'
  if (-not (test-path $tool)) {
    $tool = join-path $path 'MSBuild\15.0\Bin\MSBuild.exe'
    if (-not (test-path $tool)) {
      throw 'Failed to find MSBuild'
    }
  }
  & $tool $args
}

The asterisk indicates to search all products. It is not, however, a wildcard for pattern matching.