Skip to content

Instantly share code, notes, and snippets.

@piers7
Created November 18, 2015 01:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save piers7/393ce7d0d3e115f140f1 to your computer and use it in GitHub Desktop.
Save piers7/393ce7d0d3e115f140f1 to your computer and use it in GitHub Desktop.
PowerShell - reliably detect failure from external scripts
<#
.Synopsis
Detects failure from an external script has failed based on both $? and $LASTEXITCODE checking
Tested with a .net console app in 4 modes:
- no stderr, exit 0 (should be the only passing case)
- stderr, exit 0 ($? should indicate failure)
- no stderr, exit 1 ($LASTEXITCODE should indicate failure)
- stderr, exit 1 (both $? and $LASTEXITCODE should indicate failure)
See http://stackoverflow.com/questions/10666101/lastexitcode-0-but-false-in-powershell-redirecting-stderr-to-stdout-gives-n for background
#>
function exec($exe){
$eap = $ErrorActionPreference;
$global:LASTEXITCODE = 0
try{
# Temporarily change EAP
$ErrorActionPreference = 'continue';
# Redirection of the error to std out is neccesary
# to force PS console (not ISE) to monitor the error stream
# and thus trip $? if errors occur
& $exe $args 2>&1 | % { "$_" }
# Store $? in case any of the other statements change it
$errorsRaised = !$?
}finally{
$ErrorActionPreference = $eap;
}
if($global:LASTEXITCODE -ne 0){
write-warning ('Failed with exit code ' + $global:LASTEXITCODE)
}elseif($errorsRaised){
write-warning 'Failed (errors written to std out or non-zero exit code)'
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment