7

How do I pass my variable VAR_A to an embedded powershell script in a jenkins pipeline ?

e.g.

def VAR_A = 'test'
def mystatus = powershell(returnStatus: true, script: '''
                Write-Host "My result: '$VAR_A'" '''


withEnv(["VAR_A=test"]) {
def mystatus = powershell(returnStatus: true, script: '''
                Write-Host "My result: '$VAR_A'" '''
}

both result with following output My result: ''

Note : I prefer to define my powershell script in the jenkinsfile to keep things simple.

2
  • 2
    try this: def mystatus = powershell(returnStatus: true, script: """ Write-Host \"My result: \" $VAR_A""" . for env var use $env:VAR_A Commented Oct 7, 2017 at 11:47
  • this is correct : $env:VAR_A. thanks Commented Oct 9, 2017 at 14:17

1 Answer 1

10

Try this:

node {
    powershell '''
        $VAR_A = 'test'
        Write-Host "My result: '$VAR_A'"
    '''
    withEnv(["VAR_A=envtest"]) {
        powershell '''
            Write-Host "My result is empty: '$VAR_A'"
            Write-Host "My env result: '$env:VAR_A'"
        '''
    }
}

The output is:

My result: 'test'

My result is empty: ''
My env result: 'envtest'

This was tested on Jenkins 2.73.1.

Note that:

  • $VAR_A = 'test' is declared within the first powershell '''...'''
  • env: is required to access environment variables (see about_Environment_Variables in the Microsoft Docs)
Sign up to request clarification or add additional context in comments.

1 Comment

Also be aware that a space between variable name and equal sign is not supported! withEnv(["VAR_A =envtest"]) doesn't work, where withEnv(["VAR_A= envtest"]) works.

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.