Locating MSBuild on a machine

 
 
  • Gérald Barré

MSBuild is a tool that is used to build C#, VB.NET or C++ projects. MSBuild is part of the Visual Studio. If you want to write a CI/CD pipeline for your project, you will need to find where MSBuild is installed on the CI machine.

You can install multiple versions of Visual Studio on the same machine. Also, there are multiple editions of Visual Studio (Community, Professional, Enterprise, Build Tools) that are installed in different folders by default. This means there are multiple versions of MSBuild and there are in different folders. So, you need a generic way to locate MSBuild if you want to create a build script.

Visual Studio comes with a tool named vswhere.exe that can help you to locate all Visual Studio instances on the machine. This tool is located at %ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe. You can also download vswhere from GitHub. It has multiple options to filter the results by version and installed components. Also, it can print the results in JSON which is a format that can be parsed by PowerShell.

Optionally, you can download vswhere.exe 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?Buy Me A Coffee💖 Sponsor on GitHub