How can I get an install4j installer to fail based on a Windows batch command error level - install4j

I have a windows batch cmd *.cmd file that runs sql, as part of my installer. This script returns a proper non-zero return code when the sql fails. I can't get my install4j installer to recognize the return code.
I tried two things:
I tried simply setting the failure strategy in the Run batch file action to Quit on Failures, this didn't work.
I tried setting the value of the return code in a variable (sqlReturnCode) and checking that variable in a subsequent action, that didn't work.
When I checked the installation log I'm seeing the SQL errors from stderr redirected to the log, but no matter if it succeeds or fails I see this:
[INFO] com.install4j.runtime.beans.actions.misc.RunExecutableAction [ID 72]: Variable changed: sqlReturnCode=0[class java.lang.Integer]
It's always setting that variable to zero. I DO NOT have the "Show Console Window" option checked. Is this a known bug? How can I fix/work around it?

This ended up being a problem with the cmd script being executed. The ERRORLEVEL enivonrmental variable was being set but "exit /b %ERRORLEVEL%" was not being called.
Install4j relies on the proper error level being set with the exit command.

Related

How to fix 'script returned exit code 1' when running Powershell script through Jenkins?

I have a Powershell script which runs some Unity unit tests. On fail, this returns code 1, which Jenkins interprets as a fail and stops the current build. How do I avoid this behavior?
NOTE: This question is almost identical to this one, but that one uses bash, so I cannot apply it to my problem. In other words, how do I mimic the set +e behavior in Powershell? Alternatively, how do I tell Jenkins to ignore these script return codes and to continue the build anyway?
how do I mimic the set +e behavior in Powershell
You don't have to - it's the default behavior in that calls to external programs never[1] cause execution to stop prematurely, even if they report nonzero exit codes.
Alternatively, how do I tell Jenkins to ignore these script return codes and to continue the build anyway?
Ensuring that your script always terminates with exit 0 is indeed the correct way to ensure that Jenkins doesn't consider the script call failed (though you'll lose the information as to whether or not the tests failed).
[1] It can happen accidentally, due to flawed behavior up to PowerShell 7.1: If you use a 2> redirection and $ErrorActionPreference = 'Stop' happens to be effect, a script-terminating error occurs when stderr output is actually received. There is also pending RFC #277, which suggests introducing an opt-in mechanism for properly integrating external-program calls into PowerShell's error handling.

DevOps Powershell step calls bat file successfully but returns 1

I'm calling a bat-file from a step in my yaml file. The bat is located locally on the PC where the build agent is.
The bat is called successfully. It changes the PATH-variable and runs a program afterwards. The program runs successfully however when finished the build step is still marked as unsuccessful because
[error]PowerShell exited with code '1'.
As background information as to why I'm using a bat-file instead of ps1: I'm migrating our current build and it runs over a central bat-file. I don't want to change it.
Is there an environment variable I can change or anything else I can do to ensure the powershell returns 0 instead of 1?
Have you considered changing the batch file exit code?
Exit codes for batch files
Use the command EXIT /B %ERRORLEVEL% at the end of the batch file to
return the error codes from the batch file
EXIT /B at the end of the batch file will stop execution of a batch file.
use EXIT /B < exitcodes > at the end of the batch file to return custom return codes.
Environment variable %ERRORLEVEL% contains the latest errorlevel in the batch file,which is the latest error codes from the last command executed. To know about Environment variable see the below note.
Note: Environment variables are a set of dynamic named values that can
affect the way, running processes will behave on a computer. For
example, an environment variable with a standard name can store the
location that a particular computer system uses to store user profile
this may vary from one computer system to another.
In the batch file , it is always a good practice to use environment
variables instead of constant values. Since the same variable get
expanded to different values on different computers.
Example:
Batch file for Copying File to a Folder
md "C:manageengine"
copy "\\sharename\foldername\samplefile.txt" "C:\manageengine"
exit /b %ERRORLEVEL%
https://www.manageengine.com/products/desktop-central/returning-error-code-on-scripts-how-to.html
EDIT: Some more thoughts about the problem- The batch file probably returned 1 as an exit code because one of the commands or programs used within it returned some kind of error code (or at least didn't return 0 exit code).
for summing up, your question was not very clear mainly because you didn't separate all the factors and variable withing your problem, thus not knowing where the problem is.
Force changing the exit code isn't the right way to fix your problem.

VSTS build definition - prevent PowerShell exit behavior causing processes termination

I have a PowerShell task in my definition that calls another script file on its own which takes care of running several things on my build agent (starts several different processes) - emulators, node.js applications, etc.
Everything is fine up until the moment this step is done and the run continues. All of the above mentioned stuff gets closed with most of the underlying processes killed, thus, any further execution (e.g. tests run) is doomed to fail.
My assumption is that these processes are somehow dependent on the outermost (temporary) script that VSTS generates to process the step.
I tried with the -NoExit switch specified in the arguments list of my script, but to no avail. I've also read somewhere a suggestion to set this by default with a registry key for powershell.exe - still nothing.
The very same workflow was okay in Jenkins. How can I fix this?
These are the tasks I have:
The last PowerShell task calls a specified PowerShell file which calls several others on its own. They ensure some local dependencies and processes needed to start executing the tests, e.g. a running Node.js application (started in a separate console for example and running fine).
When the task is done and it is successful, the last one with the tests would fail because the Node.js application has been shut down as well as anything else that was started within the previous step. It just stops everything. That's why I'm currently running the tests within the same task itself until I find out how to overcome this behavior.
I am not sure how you call the dependencies and applications in your PowerShell script. But I tried with the following command in PowerShell script task to run a Node.js application:
invoke-expression 'cmd /c start powershell -Command {node main.js}'
The application keeps running after the PowerShell script task is passed and finished which should meet your requirement. Refer to this question for details: PowerShell launch script in new instance.
But you need to remember to close the process after the test is finished.
There is the Continue on error option (Control Options section). The build process will be continued if it is true (checked), but the build result will be partially succeeded.
You also can output the error or warning by using PowerShell or VSTS task commands (uncheck Fail on Standard Error option in the Advanced section) and terminate the current PowerShell process by using the exit keyword, for example:
Write-Warning “warning”
Write-Error “error”
Write-Host " ##vso[task.logissue type=warning;]this is the warning"
Write-Host " ##vso[task.logissue type=error;sourcepath=consoleapp/main.cs;linenumber=1;columnnumber=1;code=100;]this is an error "
More information about the VSTS task command, you can refer to: Logging Commands

Azure startup task, wait for all other task to finish

I have a startup task for my webrole that download some executable file from a blob and then proceed to the installation.
From a .cmd file, I start a power shell script that download the files, then I start the file from the .cmd.
The script works fine if I run it manually through RDP after the publishing is done.
But, when running as startup script, it sometimes (often) fail at different points.
The taskType is set to background.
Last time, the error was that the command PowerShell does not exists...
Also, I use powershell -command set-executionpolicy unrestricted before running my PS script, but I read here that other task may reset this setting and make mine fail.
Quite a mess.
So that makes me think that if I could wait for all other task to perform before starting mine, it would eliminate these kinds of problems
I suppose I could check if some process is running and wait for it to finish, but I have no clue wich process to check.
Or maybe there's another solution.
~edit~
I read here that the error about powershell not existing may be caused by the batch file being saved as UTF-8 in visual studio. I re-writed it from scratch in notepad++ and made sure it is save as ANSI. Then, same error. The full message is :
'PowerShell' is not recognized as an internal or external command,
operable program or batch file.
Again, the script run perfectly from command line in remote desktop.
It would be possible to set an environment variable at the end of the script that is required to finish, then in the script which is awaiting the dependencies, loop until the environment variable is set, then kick off its activities.
You could also run everything from a single powershell script and use the '-asjob' switch on your installer statement, use the 'wait-job' cmdlet to block until the task is complete then carry on. Powershell also offers a '?!' operator which ensures the last statement executed properly.
This might be caused by an encoding issue. As mentioned in this answer you should save your file in ASCII to ensure correct interpretation of your script.
From the linked answer:
Open your whatever.cmd file with your VS 2012 Ultimate. Click on File->Save whatever.cmd as -> on the dialog there is little arrow next to the [save] button. It will show up a menu that will have the option Save with Encoding.
Select it. Now choose "US-ASCII Codepage 20127" from the list of available encodings.

How do I get errors to propagate in the TeamCity PowerShell runner

I have a TeamCity 7 Build Configuration which is pretty much only an invocation of a .ps1 script using various TeamCity Parameters.
I was hoping that might be a simple matter of setting:
Script
File
Script File
%system.teamcity.build.workingDir%/Script.ps1
Script execution mode
Execute .ps1 script with "-File" argument
Script arguments
%system.teamcity.build.workingDir% -OptionB %BuildConfigArgument% %BuildConfigArg2%
And then I would expect:
if I mess up my arguments and the script won't start, the Build fails
if my Script.ps1 script throws, the Build fails
If the script exits with a non-0 Error Level I want the Build to Fail (maybe this is not idiomatic PS error management - should a .ps1 only report success by the absence of exceptions?)
The question: It just doesn't work. How is it supposed to work? Is there something I'm doing drastically wrong that I can fix by choosing different options?
As doc'd in the friendly TeamCity manual:
Setting Error Output to Error and adding build failure condition
In case syntax errors and exceptions are present, PowerShell writes them to stderr. To make TeamCity fail the build, set Error Output option to Error and add a build failure condition that will fail the build on any error output.
The keys to making this work is to change two defaults:
At the top level in the Build Failure Conditions, switch on an error message is logged by build runner:
In the [PowerShell] Build Step, Show advanced options and set Error output: Error
In 9.1 the following works (I wouldn't be surprised if it works for earlier versions too):
create a PowerShell Build Step with the default options
change the dropdown to say Script: Source code
Add a trap { Write-Error "Exception $_" ; exit 98 } at the top of the script
(Optional but more correct IMO for the kind of scripting that's appropriate for within TeamCity build scripts)
Show advanced options and switch on Options: Add -NoProfile argument
(Optional, but for me this should be the default as it renders more clearly as suggested by #Jamal Mavadat)
Show advanced options and switch on Error output: Error
(ASIDE #JetBrains: if the label was "Format stderr output as" it would be less misleading)
This covers the following cases:
Parse errors [bubble up as exceptions and stop execution immediately]
Exceptions [thrown directly or indirectly in your PS code show and trigger an exit code for TC to stop the build]
An explicit exit n in the script propagates out to the build (and fails it if non-zero)
There is an known bug in TeamCity that causes the behavior that the original poster noticed.
It is easy to work around, however.
At the end of your PowerShell script, add output indicating that the end of the script has been reached:
Echo "Packaging complete (end of script reached)"
Then, set up a new Build Failure Condition on your build to fail if the text you are echoing is NOT present in the output.
You're over-thinking things. Try this:
Script
File
Script File
Script.ps1
You don't need to give this a path - by default, it's relative to the checkout directory.
Script execution mode
Put script into PowerShell stdin with "-Command -" arguments
This is exactly what I use to run a bunch of powershell scripts within Teamcity.
Update
I missed the bit in the original post about having failures in the powershell script fail the build. Apologies!
I've solved that part of the puzzle in two different ways.
For regular powershell scripts
Wrap the main code block in a try...catch; if an exception occurs, return a non-zero integer value. For successful execution, return 0.
This convention of returning zero for success dates back a very long way in history - it's used by Unix/Linux systems, DOS, CP/M and more.
For PSake build scripts
Use a wrapper powershell script to invoke psake and directly set the result of the teamcity build by writing a response message to stdout.
At the start of the script, define a status message that represents failure:
$global:buildResult = "#teamcity[buildStatus status='FAILURE' text='It died.']
Within the psake script, update $global:buildResult to indicate success in a dedicated task that's run last of all.
$global:buildResult = "#teamcity[buildStatus status='SUCCESS' text='It lives.']
At the end of the wrapper script, output the status message
write-host $global:buildResult
If anything in the build script fails, that last task won't run, and the default message (indicating failure) will be output.
Either way, Teamcity will pick up on the message and set the build status appropriately.
An alternative to the accepted answer that works for me On TeamCity 9 (I don't like changing the 'Build Failure Conditions' option as it affects all build steps):-
I wanted PowerShell errors to fail the build step, but with a pretty message.
So I wanted to throw an error message AND return an error code.... try / catch / finally to the rescue.
EDIT for clarity: This script is supposed to fail. It is demonstrating that it is possible to throw an exception AND to return an exit code.
So you get both, the exit code for TeamCity to deal with, and, in my case, a nice clear debug message that shows where the issue was.
My demo script:
Try {
Write-Host "Demoing the finally bit"
# Make sure if anything goes wrong in the script we get an exception
$ErrorActionPreference = "Stop"
# This will fail and throw an exception (unless you add the file)
Get-Content IDontExist.txt
}
Catch
{
# Throwing like this gives a pretty error message in the build log
throw $_
# These give less pretty/helpful error messages
# Write-Host $_
# Write-Host $_.Exception.Message
}
Finally
{
# 69 because it's more funny than 1
exit(69)
}
If newer TeamCity versions are within your reach then it is worth checking out some of PowerShell build runner improvements.
In particular, changing Error Output from default warning to error may interest you.
Just praise the lawd you don't need to work with Jenkins.. Can't use the PowerShell step for similar issues. Instead we need to use a "cmd" step that calls the following magic wrapper that will fail the step on exception and exit codes:
%SystemRoot%\sysnative\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -WindowStyle Hidden -Command "& { $ErrorActionPreference = 'Stop'; & 'path\to\script.ps1 -arg1 -arg2; EXIT $LASTEXITCODE }"
This has been superseded by options afforded by 9.x, but I'll leave it here as it definitely was bullet proof at the time and I couldn't find any other solution I liked better.
You could just do something that works. The following has been tested with
errors in the script bit
missing files
script exiting with non-0 ERRORLEVEL
In the TeamCity Powershell runner options, set it as follows:
Script File
Source code
Script source
$ErrorActionPreference='Stop'
powershell -NoProfile "Invoke-Command -ScriptBlock { `$errorActionPreference='Stop'; %system.teamcity.build.workingDir%/Script.ps1 %system.teamcity.build.workingDir% --OptionB %BuildConfigArgument% %BuildConfigArg2%; exit `$LastExitCode }"
(unwrapped version: powershell -NoProfile "Invoke-Command -ScriptBlock { $errorActionPreference='Stop'; %system.teamcity.build.workingDir%/Script.ps1 %system.teamcity.build.workingDir% --OptionB %BuildConfigArgument% %BuildConfigArg2%; exit$LastExitCode }"
Script execution mode
Put script into PowerShell stdin with "-Command -" arguments
Additional command line parameters
-NoProfile
I'm hoping against hope this isn't the best answer!
This checks the last error code and exits if is not 0.
If ($LASTEXITCODE -ne 0) {
Write-Host "The result was of the previous script was " $LASTEXITCODE
Exit $LASTEXITCODE
}
Powershell v2 atleast had an issue with the -File option messing up error codes. There is some details about how it messes up and stuff.
The answer is either switch to -Command option and/or wrap it with a bat file that checks the LastErrorCode and returns 1+ if its supposed to fail.
http://zduck.com/2012/powershell-batch-files-exit-codes/
Use something like this:
echo "##teamcity[buildStatus status='FAILURE' text='Something went wrong while executing the script...']";
For reference, take a look on Reporting Build Status from Teamcity