jenkins on windows. Declarative pipeline jenkinsfile. how to set and get correct variable values

Viewed 501

I use Jenkinsefile file to run the Stages. It is in Jenkins pipeline installed on windows, Declarative pipeline.

On the begining I do:

pipeline {
    agent { label 'master'}
    environment {
        My_build_result       = 7
    }
....
Than
        stage('Test') {
            steps {
                echo 'Testing..'

                bat """
                cd Utils
                "C:\\Program Files\\MATLAB\\R2019b\\bin\\matlab.exe" -wait -nodisplay -nosplash -nodesktop -r "run('automatic_tests\\run_test.m');"
                echo %errorlevel%
                set /a My_build_result_temp = %errorlevel%
                set My_build_result = %My_build_result_temp%
                """     
                script {
                    My_build_result = bat(returnStatus:true , script: "exit (2)").trim()                                
                    echo "My_build_result ${env.My_build_result}"               
                    if (My_build_result != 0) {
                        echo "inside if"
                    }
                }
            }
        }

The variable My_build_result get value 7 at the begining Inside the bat section, it suppose to get value 0 from %errorlevel% Inside the script section it suppose to get value 2 BUT in the echo "My_build_result ${env.My_build_result}" I get print of 7 (and it goes inside the if sentense)

How do I define variable that can be set value in bat""" """ and in script """ """ section of the stage and also be familiar in another stages and in the post { always { .. }} at the end ???

BTW: add env.before My_build_result (env.My_build_result ) does not work Thanks a lot

1 Answers

In the first bat call, you are setting the environment variable only inside of the batch script environment. Environment variable values that are assigned through set don't persist when the script ends. Think of these like local variables. Simply use returnStatus: true to return the last value of ERRORLEVEL. There is no need to use %ERRORLEVEL% in the batch script here.

steps {
    script {
        My_build_result = bat returnStatus: true, script: """
            cd Utils
            "C:\\Program Files\\MATLAB\\R2019b\\bin\\matlab.exe" -wait -nodisplay -nosplash -nodesktop -r "run('automatic_tests\\run_test.m');"
        """
        // My_build_result now has the value of ERRORLEVEL from the last command
        // called in the batch script. 
    }
}

In the 2nd bat call the 1st mistake is to call the trim() method. Result type of bat step is Integer, when returnStatus: true is passed. The trim() method is only available when returnStdout: true is passed in which case the result type would be String. The 2nd mistake is to use brackets around the exit code value. The fixed code should look like:

My_build_result = bat returnStatus: true, script: "exit 2"
// My_build_result now equals 2
Related