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
- Use the
exit
keyword followed by the numeric exit code you want to return.exit <code>
- 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
- Standard Exit Codes:
- Use
0
for success. - Use non-zero values (e.g.,
1
,2
, etc.) for different types of errors.
- Use
- Error Handling:
- Use
try-catch
blocks to handle errors and set appropriate exit codes.
- Use
- Script Scope:
- The
exit
keyword terminates the current PowerShell session or script scope. Use carefully when calling functions or running in interactive sessions.
- The
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 returns0
by default. - For scripts that use
throw
or$ErrorActionPreference = "Stop"
, you may need to handle errors explicitly and set a custom exit code.
Let me know if you’d like further clarification or help with a specific scenario!