【问题标题】:Pass the output of PowerShell script to Jenkins Parameters将 PowerShell 脚本的输出传递给 Jenkins 参数
【发布时间】:2021-12-07 15:22:18
【问题描述】:

我正在尝试获取 Vsphere 模板列表并将它们用作 Jenkins 中的参数。 我尝试过使用函数并运行 PowerShell 命令。

def findtemplates() {
  def $vmTemplate = "powershell -command 'Connect-VIServer -server server -User user -Password pass -Force; Get-Template | select name'"
    return $vmTemplate
}

在参数部分:

      parameters {
    choice(name: 'Template', choices: findtemplates(), description: 'test')
  }

但不起作用。 任何帮助将不胜感激。

【问题讨论】:

    标签: powershell jenkins groovy jenkins-pipeline jenkins-groovy


    【解决方案1】:

    使用参数returnStdout: true 调用powershell 步骤(或pwsh 用于PS 7+)以获取PowerShell 命令的输出:

    def findtemplates() {
      return powershell( returnStdout: true, script: '''
          Connect-VIServer -server server -User user -Password pass -Force
          Get-Template | select name'
        ''')
    }
    

    注意使用''' 将多行脚本传递给powershell 步骤。

    我猜你硬编码用户名和密码只是为了简洁。更完整的示例如下所示:

    def findtemplates() {                       
      withCredentials([ usernamePassword( credentialsId: 'ReplaceWithYourCredentialsId',
                                          usernameVariable: 'VIServerUser', 
                                          passwordVariable: 'VIServerPassword') ]) {
                    
         return powershell( returnStdout: true, script: '''
           Connect-VIServer -server server -User $env:VIServerUser -Password $env:VIServerPassword -Force
           Get-Template | select name'
         ''')
                            
      }
    }
    

    出于安全原因,请注意使用环境变量而不是 Groovy 字符串插值(请参阅String interpolation)。

    【讨论】:

    • 谢谢,它解决了我的问题。唯一缺少的是将代码放在节点块中。节点{}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-01
    • 2015-06-07
    • 2017-05-08
    • 2019-07-07
    • 2013-04-27
    相关资源
    最近更新 更多