Search code examples
powershellerror-handlingexit-codestart-process

Ignoring powershell script failure for a particular line


I have a powershell script that defines $ErrorActionPreference = "Stop"
But i also have a start-process call that target a process that returns a non-standard exit code on success (1 instead of 0). As a result of this, the script is failing even when the start-process is ok. I tried to append the -ErrorAction "Continue" parameter in the start-process call but it didn't solve the problem.

The problematic line looks like this:

$ErrorActionPreference = "Stop"
...
start-process "binary.exe" -Wait -ErrorAction "Continue"
if ($LastExitCode -ne 1)
{
   echo "The executable failed to execute properly."
   exit -1
}
...

How could I prevent start-process from making the whole script fail.


Solution

  • Start-Process doesn't update $LASTEXITCODE. Run Start-Process with the -PassThru parameter to get the process object, and evaluate that object's ExitCode property:

    $ErrorActionPreference = "Stop"
    ...
    $p = Start-Process "binary.exe" -Wait -PassThru
    if ($p.ExitCode -ne 1) {
      echo "The executable failed to execute properly."
      exit -1
    }