4

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??

snieguu
  • 2,073
  • 2
  • 20
  • 39
SeWaNsX
  • 87
  • 2
  • 8

3 Answers3

4

I've used this:

powershell('''                       
 "env.PACKAGE_VERSION='$newversion'" | Out-File packageVersion.properties -Encoding ASCII
''')

later:

script {
  load('packageVersion.properties')}

using the value:

echo("---- PACKAGE_VERSION: ${env.PACKAGE_VERSION} ----")
BuckTheBug
  • 428
  • 4
  • 6
3

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/

tenpn
  • 4,556
  • 5
  • 43
  • 63
1

I'm not familiar with Jenkins but have you tried using Write-output $value1 or return $value1?

I found that in some of my powershell scripts, anything I output is captured and returned to the calling function. Of course, you will need to somehow save the value on the Jenkins side to reuse it.

Another way would be to save the value to a file and read it from the file. You could do it using $value1 | out-file C:\temp\temp.txt and then read it using Get-Content C:\temp\temp.txt in a separate script.

Shadowzee
  • 537
  • 3
  • 15
  • i try but not works ... almost in jenkins. the second way works but with a file txt and laster read it and use it ... – SeWaNsX Jan 09 '19 at 12:42