Running MSBuild using a Powershell Script

Created 28 July 2010 15:58
I wanted to build a Visual Studio solution using MSBuild using a Powershell script. Surprisingly, I couldn't find a reference on the web that actually worked for me. I thought I'd post it here for future reference, as it applies to the execution of any executable from within Powershell. It was "Invoke-Expression" that I hadn't used before.
$baseDir = "C:\Test"
$outputFolder = $baseDir + "Output"
$msbuild = "C:\Windows\Microsoft.NET\Framework64\v3.5\MSBuild.exe"
$options = "/noconsolelogger /p:Configuration=Release"
$releaseFolder = $baseDir + "MyProject\bin\Release"

# if the output folder exists, delete it
if ([System.IO.Directory]::Exists($outputFolder))
 [System.IO.Directory]::Delete($outputFolder, 1)

# make sure our working directory is correct
cd $baseDir

# create the build command and invoke it 
# note that if you want to debug, remove the "/noconsolelogger" 
# from the $options string
$clean = $msbuild + " ""MySolution.sln"" " + $options + " /t:Clean"
$build = $msbuild + " ""MySolution.sln"" " + $options + " /t:Build"
Invoke-Expression $clean
Invoke-Expression $build

# move all the files that were built to the output folder
[System.IO.Directory]::Move($releaseFolder, $outputFolder)
Anonymous on 10 February 2011 at 01:19
Very useful post - helped me get up and running with this quickly.
Anonymous on 18 June 2011 at 01:26
Super helpful. Thank you for posting.
Anonymous on 16 December 2011 at 13:03
Hi, How would you add the /p:DefineConstants="FLAG1;FLAG2" option to the msbuild command u have mentioned above? When I used it like this:

$mconsts = " /p:DefineConstants="
$mmore = $mconsts + $flag1
$build = $msbuild + " ""MySolution.sln"" " + $options + " " + $mmore + " /t:Build"
power shell barfs saying: The term 'MY_DEBUG2_FLAG' is not recognized as the name of a cmdlet, function, script file, or operable program.

Any help on this?