Locating MSBuild on a machine

 
 
  • Gérald Barré

MSBuild is a tool used to build C#, VB.NET, and C++ projects. It is bundled with Visual Studio. If you want to write a CI/CD pipeline for your project, you need to find where MSBuild is installed on the CI machine.

You can install multiple versions of Visual Studio on the same machine, and there are multiple editions (Community, Professional, Enterprise, Build Tools) that each install to different folders by default. This means multiple versions of MSBuild can exist in different locations, so you need a reliable way to locate it when writing a build script.

Visual Studio includes a tool called vswhere.exe that can locate all Visual Studio instances on the machine. It is located at %ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe. You can also download vswhere from GitHub. It supports filtering by version and installed components, and can output results in JSON for easy parsing with PowerShell.

Optionally, you can download the latest vswhere.exe directly from GitHub:

PowerShell
# Find the latest release
$(Invoke-WebRequest "https://github.com/microsoft/vswhere/releases/latest").BaseResponse.RequestMessage.RequestUri -match "tag/(.*)$"

# Download the vswhere.exe
Invoke-WebRequest "https://github.com/microsoft/vswhere/releases/download/$($Matches[1])/vswhere.exe" -OutFile "vswhere.exe"

Then, you can use vswhere.exe to find the location of MSBuild:

PowerShell
& "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" `
    -version "[16.0,18.0)" <# Visual Studio 2019 and 2022 #> `
    -products *  <# Edition of Visual Studio to search for
                    https://learn.microsoft.com/en-us/visualstudio/install/workload-and-component-ids?WT.mc_id=DT-MVP-5003978 #> `
    -requires Microsoft.Component.MSBuild `
    -prerelease            <# include prerelease versions #> `
    -latest                <# Only return the newest version that matches the criteria #> `
    -utf8 -format json     <# print the results in JSON format #>

Output of vswhereOutput of vswhere

You can then parse the JSON output using ConvertFrom-Json and extract the installationPath property of the desired Visual Studio instance:

PowerShell
$vs = & "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -version "[16.0,18.0)" -products * -requires Microsoft.Component.MSBuild -prerelease -latest -utf8 -format json | ConvertFrom-Json
$msbuild = Join-Path $vs[0].installationPath "MSBuild" "Current" "Bin" "MSBuild.exe"

Finally, you can run an msbuild command:

PowerShell
& $msbuild /t:build mysolution.sln

#Additional resources

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?