LastExitCode in PowerShell

Migel Hewage Nimesha Jan 30, 2023 Mar 20, 2022
  1. Use of $? in a PowerShell Environment
  2. $LastExitCode as an Error Handler in PowerShell
LastExitCode in PowerShell

This article will focus on $? and $lastexitcode commands and their difference in PowerShell.

Every scripting and programming language enables error handling, error catching, and managing in their scripts. We can use the $? command and the $lastexitcode command for error handling.

Use of $? in a PowerShell Environment

It is important to understand the $? command before using it here. According to PowerShell definitions of different commands, the $? command can be used as an error handler.

Based on the last command executed, it returns a Boolean value, True or False. If the last command executed in the script is successful, it returns true; otherwise, it returns false.

One execution of this command is shown in the execution code below.

PS C:\Users> cmd /c "exit 5"
PS C:\Users> $?
PS C:\Users> cmd /c "exit 0"
PS C:\Users> $?

This command example uses exit with code 5 and exit with 0. Exit with code 0 usually indicates a successful execution and termination of the script.

The following image shows the output of the exit commands and the error handling done by $? commands.

powershell error handling command

There is a difference in $lastexitcode and the $?. However, it is also used for error handling.

$LastExitCode as an Error Handler in PowerShell

There is a difference in error handling used when the command is internal and when the command is external.

You will use the $lastexitcode when the command is external. This is because this command applies only to external scripts and commands.

By definition, $lastexitcode shows the last Windows-based program’s exit code.

The following script shows $lastexitcode after the same command as above.

PS C:\Users> $LastExitCode
PS C:\Users>

The following image shows the same execution and output.

lastexitcode error handler

As the last command executed in the previous command gave true as the output, this would show the successful execution of the last command. When the previous script was true, the $LastExitCode output would always be 0.

But, when it is unsuccessful, it would be 1 or any other integer returned by the external script because the $LastExitCode command is not binary, unlike the $? command.

Migel Hewage Nimesha avatar Migel Hewage Nimesha avatar

Nimesha is a Full-stack Software Engineer for more than five years, he loves technology, as technology has the power to solve our many problems within just a minute. He have been contributing to various projects over the last 5+ years and working with almost all the so-called 03 tiers(DB, M-Tier, and Client). Recently, he has started working with DevOps technologies such as Azure administration, Kubernetes, Terraform automation, and Bash scripting as well.