4

I have a simple Jenkins pipeline which calls a PS file. The Ps file returns some values and I would like to know if I can save those values onto variables that can be used used within my pipeline steps.

    pipeline {
    agent {label 'agent'}        
stages {

       stage("first script"){
            steps {
                echo "Current agent  info: ${env.AGENT_INFO}"
                script {
                        def msg = powershell(returnStdout: true, script: '.\\Get-Guid.ps1')
//                        def msg = powershell(returnStdout: true, script: 'ipconfig')
                            println "The new GUID is:  ${msg}"
                            my_guid = msg
                            env.my_guid  = my_guid
                  //      print msg#
                  echo "Is my GUID: ${my_guid}"

                }
            }
        }


        stage("Second Script"){
            steps {
                script {
                   def msg = powershell(returnStdout: true, script: 'write-output "Powershell is Great"')
             //       println msg
                }
            }
        }
    }
}

The contents of Get-GUID.ps1 is as follows.

$buildguid = (New-Guid).Guid
$name = "Tom"

Write-Output $buildguid
Write-Output $name

Ideally, I would like to have the value or buildguid stored in a seperate varialbe from the pipeline and name in a seperate variable as well.

2

1 Answer 1

2

Modify your Get-GUID.ps1 script to write output to one file or multiple files and retrieve value from them.

Your Get-GUID.ps1 file will look like this:

$buildguid = (New-Guid).Guid
$name = "Tom"

Write-Output $buildguid | Out-File "buildguid.txt"
Write-Output $name | Out-File "name.txt"

The output can be retrieved from the pipeline like this:

pipeline {
    agent { label 'windows' }
    stages {
        stage("Populate variables")
        {
            steps {
                script {
                    def result = powershell returnStatus:true, script: '.\\Get-GUID.ps1'
                }
            }
        }
        
        stage("Display variables")
        {
            steps {
                script {
                    def guid = powershell returnStdout:true, script: 'Get-Content .\\buildguid.txt'
                    def name = powershell returnStdout:true, script: 'Get-Content .\\name.txt'
                    print guid.trim()
                    print name.trim()
                }
            }
        }
    }
}

Note: Don't forget to trim() your output when retrieved.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.