56
votes

How can I run an executable in PowerShell and through an if statement determine whether it succeeded or failed?

More specifically I'm trying to get devenv.exe to build a solution from a PowerShell script and I need to know whether it succeeded or failed. By failed, I mean that the build has failed and I'm assuming devenv is sending something out to the shell (possibly in the stderr stream?)

I tried using &, Invoke-Expression and Invoke-Item and managed to get all of them to run the exe. But I was never able to get feedback on success / failures.

2
Is there a reason why you don't use msbuild.exe to build the solution instead of devenv.exe? - Filburt
The only reason is that I'm not proficient enough in using msbuild. I do have a build machine building my solutions but I don't know how to reuse the build definitions for my local machine :| - urig
If you want to give it a try here's a reference to how to use msbuild for building solutions: msdn.microsoft.com/en-us/library/z7f65y0d.aspx - Filburt
Thanks Filburt. Will definitely give it some time. - urig

2 Answers

86
votes

Have you tried using the $LASTEXITCODE variable? It will contain the exit code of the last .exe that was invoked.

14
votes
.\YOUREXE.exe
if($LASTEXITCODE -eq 0)
{
    Write-Host "The last PS command executed successfully"
} 
else 
{
    Write-Host "The last PS command failed"
}