Visual Studio Online's build: Azure Powershell fail the build

visual_studio_online_build_tasks Visual Studio Online has many tasks: tasks for building .NET solutions, tasks for building Android, tasks for running bash scripts, tasks for running batch files.  If you want to run in the context of your Azure subscription, you use the Azure Powershell task.  I use this task to do some funny footwork in deploying successful results to an Azure Web App.

The problem:

& $env:BUILD_SOURCESDIRECTORY\the.exe
$e = $LASTEXITCODE
Write-Host "Exit code: $e"
exit $e

So I’m cruising along, my exe returns a non-zero status code to mean “please fail the build”, and Visual Studio Online happily succeeds.  I’m clearly returning 1 from my Azure Powershell task, but it’s not getting the message. A few hours of pulling out grey hairs, and I’m given a great gift from

Chris Patterson.  (Scott Hunter: your team rocks.)  Turns out that the Azure Powershell task isn’t run from powershell.exe, so it doesn’t harvest exit codes.  The solution was simple once he handed it to me.

The Solution:

& $env:BUILD_SOURCESDIRECTORY\the.exe
$e = $LASTEXITCODE
Write-Host "Exit code: $e"
if ($e -ne 0) {
    Write-Error -Message "##[error]BUILD FAILED: $e"
}
exit $e

By using Write-Error, the build correctly fails when it needs to, and life is good.  Chris mentions that he’d like to see it work differently, but it didn’t make RTM.  If you’d like this idea to come in-the-box, vote up my Pull Request … because the task is open-source.  Awesome!