learner
learner

Reputation: 979

Getting output values from powershell script from jenkins pipeline

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.

Upvotes: 4

Views: 5091

Answers (1)

Aditya Nair
Aditya Nair

Reputation: 572

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.

Upvotes: 2

Related Questions