- 1 year ago
How to use Jenkins pipeline variable into powershell or cmd code?
To use a Jenkins pipeline variable in PowerShell or CMD code within a Jenkins pipeline, you can utilize string interpolation or concatenation to include the variable value in the script. Here's an example of how you can achieve this:
Using PowerShell:
groovypipeline {
agent any
environment {
myVariable = 'Hello, Jenkins!'
}
stages {
stage('Example') {
steps {
powershell '''
$myVariable = "${env.myVariable}"
Write-Host $myVariable
'''
}
}
}
}
In this example, we define the myVariable
environment variable within the environment
block. Then, within the PowerShell script step, we access the Jenkins pipeline variable using $env.myVariable
and assign it to a local PowerShell variable. Finally, we use Write-Host
to display the value of the variable.
Using CMD:
groovypipeline {
agent any
environment {
myVariable = 'Hello, Jenkins!'
}
stages {
stage('Example') {
steps {
bat '''
set myVariable=%myVariable%
echo %myVariable%
'''
}
}
}
}
In this example, we define the myVariable
environment variable within the environment
block. Within the CMD script step, we use set
to assign the value of the Jenkins pipeline variable to a local CMD variable (%myVariable%
). Then, we use echo
to display the value of the variable.
By using string interpolation or concatenation ("${env.myVariable}"
or %myVariable%
, respectively), you can access the Jenkins pipeline variable and incorporate its value into your PowerShell or CMD code within the Jenkins pipeline.