Run Powershell script from file in Jenkins pipeline
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:
- Env vars set in the top-level
environment
block can't be changed during the run. (At least that is my experience.) - Env vars can only be Strings. There are tricks you can play to get maps to work, but they're tricks.
- If you want to set an env var that's changeable throughout the pipeline's scope, you have to do it in a
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' } } } ...
- You can also set env vars scoped only to that stage. In my experience, these are not evaluated before entering the actual steps block - ie, they will not be set during
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/