Understanding the $LASTEXITCODE and exit codes in PowerShell

When working with Azure DevOps pipelines you will often want your tasks to run PowerShell scripts. Since the execution of the upcoming tasks can be dependent to the result of the current task, your script will have to inform about success or error.

For this task you can use exit codes, which indicate the success or failure of a command or script. We are also going to learn how to use the $LASTEXITCODE variable to determine the outcome of your commands.

What is $LASTEXITCODE?

$LASTEXITCODE is an automatic variable in PowerShell that stores the exit code of the last executed command. It is particularly useful when you need to check the result of an external command or a script that you have run. Exit codes are integers that provide information about the success or failure of a command.

The two most common exit codes are:

Here’s an example of how to use $LASTEXITCODE in a task of an Azure DevOps pipeline, after calling a .ps1 script:

if ($LASTEXITCODE -eq 0) {
    Write-Output "The command was successful."
} else {
    Write-Output "The command failed with exit code $LASTEXITCODE."
}

Conclusion

By using the $LASTEXITCODE variable, you can easily check the result of your commands and take appropriate actions based on their success or failure.

Feel free to ask any questions or leave your comment below.

comments powered by Disqus