Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is PowerShell's $LastExitCode Variable Always 0 After a Failed Build with MSBuild?

I've noticed that when MSBuild fails, the value of the $LastExitCode variable is always 0. I'm on Windows 7, with MSBuild v4.0 and PowerShell 2.0. This is my MSBuild scritpt:

<?xml version="1.0" encoding="UTF-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0" DefaultTargets="Fail">
    <Target Name="Fail">
        <Error />
    </Target>
</Project>

When I run:

msbuild.exe MyProject.csproj

I can see in the output that MSBuild fails, but when I check $LastExitCode, it has a value of 0. Anyone know what might be going on?

I've tried setting $(ErrorActionPreference) to Stop, but that didn't work. I re-opened a new PowerShell window, that didn't work either.

like image 414
Aaron Jensen Avatar asked Apr 09 '11 07:04

Aaron Jensen


2 Answers

I ran into a problem recently. It turned out some code in my profile that was updating $lastexitcode- the code was a custom prompt generator. Try running powershell without your profile with "powershell -noprofile" to see if the problem could be code in your profile.

Consider checking the value $?
Its false if $lastexitcode is nonzero... It works for me even when $lastexitcode did not.

like image 182
Frank Schwieterman Avatar answered Sep 27 '22 16:09

Frank Schwieterman


$LASTEXITCODE is for win32 executables and $? is for PS commands. What is the value of %errorlevel% when you run the msbuild.exe from cmd?

Please read http://techibee.com/powershell/what-is-lastexitcode-and-in-powershell/1847 if you want to know more about difference between these two special variables.

like image 41
Sitaram Pamarthi Avatar answered Sep 27 '22 18:09

Sitaram Pamarthi