I'm using Jenkins PowerShell plugin to build a project.
However, I found that Jenkins always considers my build successful no matter what I type inside Windows PowerShell
command.
Here's an example:
As you can see, asdf
isn't a legal command. Jenkins should give me FAILURE
after the build.
But the console output gives me:
Started by user admin
Building in workspace C:\Users\Administrator\.jenkins\jobs\Test\workspace
[workspace] $ powershell.exe -NonInteractive -ExecutionPolicy ByPass "& 'C:\Users\ADMINI~1\AppData\Local\Temp\hudson2092642221832331776.ps1'"
The term 'asdf' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Users\ADMINI~1\AppData\Local\Temp\hudson2092642221832331776.ps1:1 char:5
+ asdf <<<<
+ CategoryInfo : ObjectNotFound: (asdf:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Finished: SUCCESS
I think the execution result of PowerShell should depend on $lastexitcode
.
Is this a bug of PowerShell plugin?
Ultimately, I had to resort to the following configuration in Jenkins as none of the solutions here worked for me. Chris Nelson's answer got me on the right track. We're invoking chef-client remotely so we had to do a little magic to get the remote PS session to talk the local and then pass status on to Jenkins.
Of course, you'll have to supply your own evironment variables! :)
For me, I wanted the script to stop and fail in Jenkins soon as it hit an error. This was accomplished by adding this to the start of the script:
This is discussed here: How to stop a PowerShell script on the first error?
I want to add here that I just ran into a quirk: you must have the powershell script end with
exit
and notreturn
.My jenkins pipe looked like:
I was using
if(error condition) { return 1 }
and while the 1 was showing up as the return value in the jenkins console, it was not failing the build. When i usedif(error condition) { exit 1 }
, the build failed as expected.I think this is a helpful addition to this thread - the need to use
exit
and notreturn
. But I don't understand this part: the pipe is checking forresult
to be non-zero. What is the difference betweenexit
andreturn
in a powershell directive that makesif(result) { error }
not work as expected when usingreturn
?As of 1.3, the plugin will not handle exceptions such as those from missing commands. You can do this yourself with
try/catch
:See MSDN for more.
Per the latest version of the plugin (Version 1.3 Sept 18 2015), you must use $LastExitCode to fail a build.
This is how I implemented RRIROWER's solution. Hope it helps.
Make sure your powershell scripts does exit with the desired value.
Run
"exit <value>"
as the last line.