Search code examples
powershelljenkinsjenkins-pipelinereturn-valueinvoke-sqlcmd

Return Value from powershell to pipeline inside pipeline


In Jenkins Pipeline i want return a value from powershell to pipeline but i dont know how

Example:

     pipeline {
        agent any 
        stages {
            stage('Return Value') { 
                steps {
                    parameters([
                        string(name: 'Value1'),
                    ])

                    powershell '''

                    parameters for conection ...
                    extra parameters ....

                    $resultQuery= Invoke-Sqlcmd @conection -QueryTimeout 0 -ErrorAction Stop
                    $value1 = $resultQuery.code <# 1000 #>
                    $message = $resultQuery.message <# Some message #>

                    ''')

                    }
                }
                stage('Another Step') { 
                steps {

                        //I want ... if ($value1 <= 1000)
                        // do something
                    }
                }
            }
        }
    }

Then i want return out of the powershell script the $value1 for use it in another step.

i try with $ENV but doesn't work

$ENV:Value1 = $resultQuery.code

any idea??


Solution

  • If you have a powershell script that just outputs the single piece of text you want, then you can use the returnStdout param to get that value back to the pipeline script:

    steps {
      script {
        env.MY_RESULT = powershell(returnStdout: true, script:'echo hi')
      }
      echo "${env.MY_RESULT}" // prints "hi"
    }
    

    more here: https://www.jenkins.io/blog/2017/07/26/powershell-pipeline/