I am trying to run a Powershell script from a file in a Jenkins pipeline.
I have read this which shows how to run powershell scripts that are entered into the pipeline, but I can't get a script to run from a file.
I have tried:
powershell returnStatus: true, script: '-File build.ps1'
and various combinations but can't figure out how to do this.
Click New Item on your Jenkins home page, enter a name for your (pipeline) job, select Pipeline, and click OK. In the Script text area of the configuration screen, enter your pipeline syntax.
msc and right click on Jenkins. Then click Properties , go to Logon tab, check mark This account and enter username and password which has admin privileges. Stop and Start Jenkins service. From now on when you will run powershell commands in Jenkins, they will be run as administrator.
Figured it out soon after, the line should have read
powershell returnStatus: true, script: '.\\build.ps1'
@bic's answer works great, and it helped me a lot. If you need to pass variables in and you don't want to use environment vars inside the script, the best way I've found is a two-liner (declarative syntax):
writeFile file: 'tempFile.ps1', text: "${libraryResource 'psScript1.ps1'}"
powershell './tempFile.ps1 -someArg $env:someArg'
So you're writing a temp file with the content of the script to the local dir. Then you're calling the script directly with powershell
, and injecting the vars in the call.
I agree it's more convenient to use environment vars in your scripts. There are a few patterns you have to keep in mind:
environment
block can't be changed during the run. (At least that is my experience.)script
block in a step. I usually set them all up in my ('init')
stage. You should then be able to use and modify these vars anywhere in the pipe - and any sub-scripts that are spawned off of it. If you have a lot of env vars, i'd recommend shunting them off to an external groovy library.
pipeline {
...
stage('init') {
steps {
script {
env.myVariable = 'some value'
}
}
}
...
when
condition evaluations. Again, just my experience, i might be wrong.
stage('A') {
environment {
stageEnvVar = 'another value'
}
steps {
...
}
}
This is the best reference I've found on Jenkins env vars: https://e.printstacktrace.blog/jenkins-pipeline-environment-variables-the-definitive-guide/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With