Skip to content

Scripting error codes

Just return $LASTEXITCODE for the code, or $_.Exception.Message for the message.
Or $Error for a list of all errors, yada yada yada… (this text exists for me to remember and update later)
This whole setup is rather rudimentary too. Dare I say perhaps, dreadful.

I’m still studying this one trying to determine the best method and piece together something, but perhaps this page might push someone towards considering how you handle errors in your own scripting work…

By default, when installing applications, they’ll produce return codes to indicate whether the installation was successful, a failure, or whether another event occurred,
such as requiring a soft/hard reboot.
When scripting application deployments, PowerShell will usually return a 0 or 1 by default, indicating whether the script ran successfully, providing either false positives,
or little information about the error that was thrown.

Below are a few code blocks demonstrating how you can add error handling/exit codes to a script.

App_removal.ps1
# Setting the $ExitCode to 0, a mandatory step
$ExitCode = 0
$msiCodes = @(
'{377DA1C7-79DE-4102-8DB7-5C2296A3E960}',
'{820D7600-089E-486B-860F-279B8119A893}'
)

We define the $ExitCode as 0 before we make any other use of it. The purpose of this is to set the standard. If the script has an unhandled error outside of our logic, it’ll return 1. In our logic, error codes will be handled with try, catch, else.


Terminal window
foreach ($code in $msiCodes) {
$keyPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$code"
if (Test-Path $keyPath) {
Write-Host "Found uninstall entry for $code"
try {
$proc = Start-Process "msiexec.exe" -ArgumentList "/x $code /qn /passive" -Wait -PassThru -NoNewWindow
if ($proc.ExitCode -ne 0) {
Write-Error "Uninstall failed for $code with exit code $($proc.ExitCode)"
$ExitCode = 10
}
} catch {
Write-Error $_.Exception.Message
$ExitCode = 11
}
} else {
Write-Output "Uninstall entry not found for $code"
$ExitCode = 101
}
}
exit $ExitCode

Highlighted are lines 7, 9, 13, and 17. Line 7 checks the output of our uninstallation program and its exit code. If it’s a non-zero exit code, the script will both Write-Error and set the variable for $ExitCode while parsing the application’s error.

The following highlights detail the error codes: 10 indicates that the path was found, but the application failed to uninstall. 11 is designed to catch any unhandled errors. 101 is expected to be returned if the test path does not exist.

Following the try block, the script then exits with the variable stored in $ExitCode, which the system stores in $LASTEXITCODE.