The following works with Visual Studio 2010 and higher[1]:
# Get the tools folder location:
# Option A: Target the *highest version installed*:
$vsToolsDir = (
Get-Item env:VS*COMNTOOLS | Sort-Object {[int]($_.Name -replace '[^\d]')}
)[-1].Value
# Option B: Target a *specific version*; e.g., Visual Studio 2010,
# internally known as version 10.0.
# (See https://en.wikipedia.org/wiki/Microsoft_Visual_Studio#History)
$vsToolsDir = $env:VS100COMNTOOLS
# Now locate msbuild.exe in the "IDE" sibling folder.
$msTestExe = Convert-Path -EA Stop (Join-Path $vsToolsDir '..\IDE\MSTest.exe')
The approach is based on this answer and is generalized and adapted to PowerShell.
It is based on system environment variables VS*COMNTOOLS
, created by Visual Studio setup, where *
represents the VS version number (e.g., 100
for VS 2010).
- Re option A:
Sort-Object
is used to ensure that the most recent Visual Studio installation is targeted, should multiple ones be installed side by side:
- The script block used for sorting first extracts only the embedded version number from the variable name (
$_.Name -replace '[^\d]'
; e.g., 100
from VS100COMNTOOLS
) and converts the result to an integer ([int]
); [-1]
then extracts the last element from the sorted array - i.e., the variable object whose names has the highest embedded version number - and accesses its value (.Value
).
The IDE
subfolder, in which MSTest.exe
is located is a sibling folder of the tools folder that VS*COMNTOOLS
points to.
If MSTest.exe
is NOT in the expected location, Convert-Path
will throw a non-terminating error by default; adding -EA Stop
(short for: -ErrorAction Stop
) ensures that the script is aborted instead.
[1]
- I've tried up to Visual Studio 2015; do let me know whether or not it works on higher versions.
- Potentially also works with VS 2008.