17

Powershell is returning a 0 exit code, when an error has occurred, if called with the -File argument. Which means my build is green when it shouldn't be :(

For example:

(in wtf.ps1)

$ErrorActionPreference = "Stop";   
$null.split()

(cmd)

powershell -file c:\wtf.ps1  
You cannot call a method on a null-valued expression.
At C:\wtf.ps1:3 char:12
+ $null.split <<<< ()
    + CategoryInfo          : InvalidOperation: (split:String) [], ParentConta
   insErrorRecordException
    + FullyQualifiedErrorId : InvokeMethodOnNull


echo %errorlevel%  
0

powershell c:\wtf.ps1  
You cannot call a method on a null-valued expression.
At C:\wtf.ps1:3 char:12
+ $null.split <<<< ()
    + CategoryInfo          : InvalidOperation: (split:String) [], ParentConta
   insErrorRecordException
    + FullyQualifiedErrorId : InvokeMethodOnNull


echo %errorlevel%  
1

Any ideas?

(I've tried pretty much every idea from the first 2 pages of this: https://www.google.co.uk/search?q=powershell+file+argument+exit+code already)

2 Answers 2

13

In the script, use the exit keyword with a number of your choice:

exit 34

Here's the script I used to test this:

## D:\Scripts\Temp\exit.ps1 ##
try{
    $null.split()
}
catch
{
    exit 34
}

exit 2
#############################

# launch powershell from cmd 
C:\> powershell -noprofile -file D:\Scripts\Temp\exit.ps1
C:\>echo %errorlevel%
34
Sign up to request clarification or add additional context in comments.

2 Comments

If it's a terminating error, the exit never gets called :( And, even if I try/catch and exit >0, if I call it with -File I lose the exit code.
Hmm, your example works for me. And yet, my build is still green. I'll see if I can work out what's different.
12

It is a known problem. Workarounds are calling the script with -File, using the -Command parameter (and adding ; exit $lastexitcode if you also have your own exit codes) or turning them into exit codes like Shay is showing or the example using trap below. See here for more information.

trap
{
    $ErrorActionPreference = "Continue";   
    Write-Error $_
    exit 1
}

$ErrorActionPreference = "Stop";   
$null.split()

1 Comment

This workaround works well in Jenkins. I simply used the following Windows PowerShell command: PowerShell -File "srcipt.ps1"; exit $lastexitcode;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.