8

Is there a way to use groovy variables inside a powershell script? My sample script is as following..

  node {
  stage('Invoke Installation') {
  def stdoutpowershell
  def serverName = env.fqdn
  withEnv(['serverName =  $serverName']) {
      echo "serverName : $serverName"
      stdoutpowershell = powershell returnStdout: true, script: '''
          write-output "Server is $env:serverName"
      '''
  }
  }
2
  • $envserverName -> $env:serverName Commented Sep 28, 2017 at 15:52
  • @BenH it looks like I made a small mistake while creating sample code block. It should be as you mentioned so I have updated the script but the problem here is not that. Commented Sep 28, 2017 at 20:58

2 Answers 2

11

You cannot interpolate variables in single quotes or triple-single quotes. Use triple-double-quotes:

  stdoutpowershell = powershell returnStdout: true, script: """
      write-output "Server is $env:serverName"
  """
Sign up to request clarification or add additional context in comments.

1 Comment

Is there any way to have more then one statement inside , like whole powershell script block loke ~~~ stdoutpowershell = powershell returnStdout: true, script: """ write-output "Server is $envserverName" write-output "serevelkjl" """ ```
2

There are two options for passing variables.

  • Env export variable
  • local variable

Add the complete script, see the below.

node {
    stage('Invoke Installation') {
        def stdoutpowershell
        def serverName = "env.fqdn"
        
        // Use Env export variable
        withEnv(["SERVER_NAME=$serverName"]) {
            stdoutpowershell = powershell returnStdout: true, script: '''
                write-output "Server is $env:SERVER_NAME"
            '''
        }
        println stdoutpowershell
        
        // Use local variable
        stdoutpowershell = powershell returnStdout: true, script: """
            write-output "Server is ${serverName}"
        """
        println stdoutpowershell
 
    } 
}

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.