Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variables to powershell script block in a jenkins pipeline

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"
      '''
  }
  }
like image 939
cansin aldanmaz Avatar asked Sep 28 '17 15:09

cansin aldanmaz


2 Answers

You can't interpolate variables in single quotes or triple-single-quotes. Use triple-double-quotes:

  stdoutpowershell = powershell returnStdout: true, script: """
      write-output "Server is $envserverName"
  """
like image 74
Rob Hales Avatar answered Nov 11 '22 11:11

Rob Hales


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
 
    } 
}
like image 45
Changemyminds Avatar answered Nov 11 '22 10:11

Changemyminds