Home > OS >  Pass the output of PowerShell script to Jenkins Parameters
Pass the output of PowerShell script to Jenkins Parameters

Time:12-11

I am trying to get a list of Vsphere templates and use them as parameters in Jenkins. I have tried using a function and running the PowerShell command.

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

And in parameter section:

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

But does not work. Any help would be appreciated.

CodePudding user response:

Call the powershell step (or pwsh for PS 7 ) with argument returnStdout: true to get the output of the PowerShell command:

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

Note the use of ''' to pass a multiline script to the powershell step.

I guess you hardcoded user name and password only for brevity. A more complete example would look like:

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

Note the use of environment variables instead of Groovy string interpolation for security reasons (see String interpolation).

  • Related