Tuesday, January 21, 2025
HomeTechReturning an exit code from a PowerShell script

Returning an exit code from a PowerShell script

In PowerShell, you can return an exit code from a script using the exit statement. This exit code can be used to indicate the success or failure of the script when it’s executed from another process, such as a batch file, another script, or a task scheduler.

How to Return an Exit Code

  1. Use the exit keyword followed by the numeric exit code you want to return.
    exit <code>
    
  2. The exit code is accessible in the $LASTEXITCODE variable or by the calling process.

Example 1: Simple Exit Code

# Script.ps1
Write-Output "Executing script"
exit 0  # Returns an exit code of 0 (success)

When you run the script:

powershell.exe -File Script.ps1
echo $LASTEXITCODE

Output:

Executing script
0

Example 2: Using Exit Codes for Error Handling

# Script.ps1
Write-Output "Starting script"

if (-Not (Test-Path "C:\SomeFile.txt")) {
    Write-Error "File not found!"
    exit 1  # Exit with error code 1
}

Write-Output "File found!"
exit 0  # Exit with success code 0

Run it and check the exit code:

powershell.exe -File Script.ps1
echo $LASTEXITCODE

If the file doesn’t exist, $LASTEXITCODE will be 1.

Example 3: Accessing Exit Code from a Batch File

If you’re calling a PowerShell script from a batch file, you can use the %ERRORLEVEL% variable to capture the exit code:

@echo off
powershell.exe -File Script.ps1
echo Exit Code: %ERRORLEVEL%

Best Practices

  1. Standard Exit Codes:
    • Use 0 for success.
    • Use non-zero values (e.g., 1, 2, etc.) for different types of errors.
  2. Error Handling:
    • Use try-catch blocks to handle errors and set appropriate exit codes.
  3. Script Scope:
    • The exit keyword terminates the current PowerShell session or script scope. Use carefully when calling functions or running in interactive sessions.
See also  Trie Data Structure | Insert and Search

Important Notes

  • $LASTEXITCODE contains the exit code of the last native executable run in PowerShell (not commands internal to PowerShell).
  • If you don’t explicitly use exit, PowerShell returns 0 by default.
  • For scripts that use throw or $ErrorActionPreference = "Stop", you may need to handle errors explicitly and set a custom exit code.
See also  Can I delete a git commit but keep the changes?

Let me know if you’d like further clarification or help with a specific scenario!

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x