What is Powershell exit code or Powershell return code?

Powershell scripts after execution return the status of execution, which is referred to as "return code" or "exit code". A successful script execution returns a 0 while an unsuccessful one returns a non-zero value that usually can be interpreted as an Error Code. The last command executed in the function or the script determines the exit status. This document provides steps on how to return error codes on Powershell scripts.

Steps to return error codes on Powershell scripts:

Use the command Exit $LASTEXITCODE at the end of the powershell script to return the error codes from the powershell script.

  • $LASTEXITCODE holds the last error code in the powershell script. It is in form of boolean values, with 0 for success and 1 for failure.
  • Exit <custom error codes> will return custom return codes from the script

Example:

Powershell script for copying file to a folder
$dest ="C: est"
New-Item $dest -type directory -force
$source ="c:samplefile.txt"
Copy-Item $source $dest
exit $LASTEXITCODE