2

I'm reading around about how to get the error from a powershell script and passing it around to the batch file calling it. The bacth file is just a Jenkins build step (Execute Win batch) and it's as simple as that:

powershell -ExecutionPolicy Unrestricted -File C:\Users\hicciuser\invoke.ps1
echo %ERRORLEVEL%
exit %ERRORLEVEL%

The powershell script is remarkably simple:

Invoke-WebRequest -Uri "https://random.url" -TimeoutSec 2
Exit $LASTEXITCODE

Turns out that, if the web request fails (times out in this case), then the %ERRORLEVEL% still seems to be 0.

If, in the script, I do Exit 1 then the %ERRORLEVEL% is set up correctly, so it seems that the Invoke-WebRequest command is not setting the right exit code on failure. Is there a simpler way to do this that I am missing?

2
  • Is your batch file code snippet part of a code block enclosed in ()? Commented Sep 16, 2015 at 14:52
  • Nope, it's just those three lines, entered in the textbox provided by Jenkins for the Exec Windows Batch build step. Commented Sep 16, 2015 at 14:56

2 Answers 2

2

In the end I went for this solution, but I would really like to know how to get a proper error code return from Invoke-WebRequest (or any other CmdLet):

$failing = 0
$Error.Clear()
try { 
    Invoke-WebRequest -Uri $url 
}
catch { 
    Write-Host $Error
    $failing = 1 
}
Exit $failing

At least I can get an exit code that's not zero and Jenkins will be happy and fail the build.

Sign up to request clarification or add additional context in comments.

Comments

0

If you want to exit with the response status code you could do something like:

try { 
    Invoke-WebRequest -Uri $url 
    Exit 0
}
catch { 
    Exit $_.Exception.Response.StatusCode.Value__
}

1 Comment

Interesting but a Timeout error does not have a status code, so it will keep Exiting 0...

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.