Created
November 18, 2015 01:06
-
-
Save piers7/393ce7d0d3e115f140f1 to your computer and use it in GitHub Desktop.
PowerShell - reliably detect failure from external scripts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
.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