powershellerror-handlingtry-catchexit-code

How To Get Exit Code From PowerShell Script


I'm trying to write a PowerShell script which sends a Slack notification whenever our build system in unable to push Docker images to Docker Hub. How can I detect and handle the Process exited with code 1 from the docker push command? I've tried the following, but the catch block isn't called.

try {
  docker push $dockerImage;
}catch{
  #Send error details to Slack
}

Solution

  • Therefore:

    docker push $dockerImage
    if ($LASTEXITCODE -ne 0) {
      #Send error details to Slack
    }
    

    See also:


    [1] The only exception is a bug, present in Windows PowerShell and historically in PowerShell (Core) up to the no-longer-supported v7.1.x, where the combination of redirecting stderr output (2> or *>) with $ErrorActionPreference = 'Stop' unexpectedly causes a script-terminating error if there's actual stderr output - see this answer.

    [2] Unfortunately, as of PowerShell 7.4.x, the automatically triggered PowerShell error is a non-terminating error rather than a statement-terminating one; the latter would make more sense, as it would allow it to be selectively caught with a try statement - see GitHub issue #18368.