在Jenkins管道中向PowerShell脚本块传递变量

lhcgjxsq  于 2023-03-29  发布在  Jenkins
关注(0)|答案(2)|浏览(179)

有没有一种方法可以在powershell脚本中使用groovy变量?我的示例脚本如下所示。

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"
      '''
  }
  }
x0fgdtte

x0fgdtte1#

不能在单引号或三重单引号中插入变量。请使用三重双引号:

stdoutpowershell = powershell returnStdout: true, script: """
      write-output "Server is $env:serverName"
  """
tp5buhyn

tp5buhyn2#

传递变量有两个选项。

  • 环境导出变量
  • 局部变量

添加完整的脚本,请参见下文。

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
 
    } 
}

相关问题