Coding Ref

How to use PowerShell exit codes

How to use PowerShell exit codes

In PowerShell, an exit code, also known as a "return code" or "error code", is a number that represents the outcome of a script or command. When a script or command finishes running, it returns an exit code that indicates whether or not it was successful.

A value of 0 typically indicates success, while other values indicate various error conditions.

Exit codes can be useful for determining the specific reason a script or command failed to run.

For example, a script might return an exit code of 1 if a required parameter was not specified, or an exit code of 2 if a specified file was not found. By checking the exit code of a script or command after it has run, you can determine if it was successful and take appropriate action based on the result.

Exit codes in PowerShell

In PowerShell, you can use the $LASTEXITCODE automatic variable to access the exit code of the last command or script that was run.

For example, you could use the following code to check the exit code of a script and take action based on the result:

# Run the script
.\my-script.ps1

# Check the exit code
if ($LASTEXITCODE -eq 0) {
  # Script was successful
  Write-Host "The script ran successfully"
} else {
  # Script failed
  Write-Host "The script failed with exit code $LASTEXITCODE"
}

In this example, the my-script.ps1 script is run using the . (dot) operator.

This runs the script in the current PowerShell session, allowing any changes it makes to take effect in the current environment.

After the script has run, the $LASTEXITCODE automatic variable is checked to see if it equals 0. If it does, the script was successful and a message is printed to the screen. If the exit code is not 0, the script failed and the exit code is printed to the screen along with an error message.

Conclusion

In PowerShell, you can use the $LASTEXITCODE automatic variable to access the exit code of the last command or script that was run.

You'll also like

Related tutorials curated for you

    How to find the Windows version from the PowerShell command line

    How to append content to a file in PowerShell

    How to get the string length of a variable in PowerShell

    How to use -filter in Get-ChildItem in PowerShell

    What is a PowerShell Hashtable?

    The difference between add-content and set-content

    What are classes in PowerShell?

    What is PowerShell Grep?

    Dictionaries in PowerShell

    How to use Format-Table in PowerShell

    How to make a directory in PowerShell

    How to sort and filter data in PowerShell