Mudit Bahedia
Mudit Bahedia

Reputation: 246

Assign value to powershell variable within Jenkins pipeline

I came across several documents on how to run a Powershell script within Jenkins pipeline and how to capture output. However I want to use the captured output for next node powershell script. e.g.

node {
    def msg = powershell(returnStdout: true, script: 'Write-Output "PowerShell is mighty!"')
}

Now I want to use msg in the next node within Powershell script. Like if we can assign it to a powershell variable and then perform operations with that variable. Any pointers on how this can be achieved?

Upvotes: 0

Views: 1026

Answers (1)

Aditya Nair
Aditya Nair

Reputation: 572

You can assign the powershell output to an environment variable and use that in the subsequent nodes:

node {
    env.msg = powershell(returnStdout: true, script: 'Write-Output "PowerShell is mighty!"')
}

node {
    def output = powershell(returnStdout: true, script: '''
        $message = ($env:msg).trim()
        Write-Output $message
    ''')
    println(output)
}

Notice the env prefix before variable msg. You can retrieve the variable within powershell in next node using $env: prefix followed by variable name. Don't forget to trim the variable (.trim()) within powershell to remove newline.

Upvotes: 1

Related Questions