Run MSBuild from powershell without specifying .Net version

797 views Asked by At

I Created a Powershell script for deploying my web application following Scott Guthrie's example explained here Automate Everything (Building Real-World Cloud Apps with Azure) Which uses this MSBuild invocation to build and publish the web app

& "$env:windir\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe" $ProjectCsproj `
/p:VisualStudioVersion=12.0 `
/p:DeployOnBuild=true `
/p:PublishProfile=$PublishXmlFile `
/p:Password=$Password

As you can see this sample assumes .Net framework version 4.0.30319 and will fail for other versions (or in the future .Net installations)

Is there a way to run this MSBuild command without assuming any specific .Net version ?

2

There are 2 answers

1
Vesper On BEST ANSWER

You might desire to find the required .NET builder from Powershell itself, since it has enough instruments in basic command set. There can be tricks if you'd use another version of .NET Framework to build your project, such as absent or obsolete/deprecated classes, properties, methods, or possibly the changes in syntax or class dependencies that will make your project unable to be built correctly under a new .NET version. You can, however, try enumerating builders and find the one that's closest to v4.0.30319. An example:

$builders= get-childitem "$env:windir\Microsoft.NET" -recurse -filter "MSBuild.exe"
$builders | select -expand FullName

This will display available MSBuild.exe filenames that can qualify to build your project. Then you parse for Framework and FrameWork64 to get either a 64-bit or a 32-bit builder, then select from the list by whatever algorithm you fancy. (I doubt it that you'll need this trick ever.)

2
Varvara Kalinina On

You could find available MsBuild.exe files like this

Dir $env:windir\Microsoft.NET\Framework -Recurse -File | ? {$_.Name -like "MSBuild.exe"} | Resolve-Path

This oneliner can be optimized even more if you set additional restrictions on dir names.

Then you could implement your own logic of choosing the version here and behaving when there is nothing found at all. For instance, you could choose the latest possible version by using regular expressions and/or .NET functions that work with paths.