Home > Software engineering >  How to load variables from a powershell script and access the same in groovy jenkinsfile pipeline va
How to load variables from a powershell script and access the same in groovy jenkinsfile pipeline va

Time:11-04

I have a requirement where I have to load powershell variables from a powershell script and store the vairable value in a groovy jenkins pipeline variable and use it thereafter to edit the name of an artifact depending on that variable's value.

powershell script: Variables.ps1 (in real scenario this has number of variables but this is just for sample)

$Version = "22.4"

jenkinsfile:

pipeline {
agent any
stages {
    stage('TestPowershell') {
      steps {
        script {
            def path = "${env.WORKSPACE}\\Power\\Variables.ps1"
            echo path
            def versionFromPowershell = powershell(returnStdout: true, script: " . '${path}'; return $Version;")
            echo versionFromPowershell
        }
      }
    }
  }
}

I get an error when I use this method as below:

groovy.lang.MissingPropertyException: No such property: Version for class: groovy.lang.Binding
at groovy.lang.Binding.getVariable(Binding.java:63)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:251)
at org.kohsuke.groovy.sandbox.impl.Checker$7.call(Checker.java:353)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:357)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:333)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:333)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:333)
at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.getProperty(SandboxInvoker.java:29)
at com.cloudbees.groovy.cps.impl.PropertyAccessBlock.rawGet(PropertyAccessBlock.java:20)
at WorkflowScript.run(WorkflowScript:26)

In the vannila powershell the script works fine and does the job, not sure why the same syntax doesn't work when invoked via jenkins build. Any help is much appreciated!

Thanks

Shobhit

CodePudding user response:

You cannot interpolate Powershell variables in a Groovy interpreter. Therefore, the script argument to the step method must contain escaped variable syntax characters such that the variable Version is interpreted by Powershell and not Groovy:

def versionFromPowershell = powershell(returnStdout: true, script: " . '${path}'; \$Version;")
  • Related