Passing variables to powershell script block in a jenkins pipeline
Asked Answered
C

2

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"
      '''
  }
  }
Chiefly answered 28/9, 2017 at 15:48 Comment(2)
$envserverName -> $env:serverNameClaycomb
@Claycomb 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.Chiefly
O
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"
  """
Oaks answered 28/9, 2017 at 16:8 Comment(1)
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" """ ```Carson
D
1

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
 
    } 
}
Dziggetai answered 6/1, 2022 at 7:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.