If you are building software on Windows, you may need to script execution of the build. PowerShell is natively available on modern Windows systems and provides a powerful and flexible scripting solution.

This script snippet can be used to locate a Visual Studio 2017 installation with MSBuild. It will take care of loading the Visual Studio environment variables, after which you can easily invoke MSBuild or another tool that will use MSBuild (like CMake).

#
# Find vswhere (installed with recent Visual Studio versions).
#
If ($vsWhere = Get-Command "vswhere.exe" -ErrorAction SilentlyContinue) {
  $vsWhere = $vsWhere.Path
} ElseIf (Test-Path "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe") {
  $vsWhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
}
 Else {
  Write-Error "vswhere not found. Aborting." -ErrorAction Stop
}
Write-Host "vswhere found at: $vsWhere" -ForegroundColor Yellow


#
# Get path to Visual Studio installation using vswhere.
#
$vsPath = &$vsWhere -latest -products * -version "[15.0,16.0)" `
 -requires Microsoft.Component.MSBuild `
 -property installationPath
If ([string]::IsNullOrEmpty("$vsPath")) {
  Write-Error "Failed to find Visual Studio 2017 installation. Aborting." -ErrorAction Stop
}
Write-Host "Using Visual Studio installation at: ${vsPath}" -ForegroundColor Yellow


#
# Make sure the Visual Studio Command Prompt variables are set.
#
If (Test-Path env:LIBPATH) {
  Write-Host "Visual Studio Command Prompt variables already set." -ForegroundColor Yellow
} Else {
  # Load VC vars
  Push-Location "${vsPath}\VC\Auxiliary\Build"
  cmd /c "vcvarsall.bat x64&set" |
    ForEach-Object {
      If ($_ -match "=") {
        $v = $_.split("="); Set-Item -Force -Path "ENV:\$($v[0])" -Value "$($v[1])"
      }
    }
  Pop-Location
  Write-Host "Visual Studio Command Prompt variables set." -ForegroundColor Yellow
}

You may need to add additional "-requires" arguments to restrict the instances of Visual Studio to those that have the required components installed. You can update the "-version" argument if you need to locate a different version of Visual Studio.

As a bonus, this snippet can be used to find CMake and add it to the PATH environment variable:

# Find CMake
If (-Not(Get-Command "cmake" -ErrorAction SilentlyContinue)) {
  $cmakePath = "${env:ProgramFiles}\CMake\bin"
  If (Test-Path "${cmakePath}\cmake.exe") {
    $env:PATH += ";${cmakePath}"
    Write-Host "CMake added to PATH: ${cmakePath}" -ForegroundColor Yellow
  } Else {
    Write-Error "CMake not found. Aborting." -ErrorAction Stop
  }
}