在Jenkins流水线中从文件运行Powershell脚本

8

我想在Jenkins管道中从文件运行Powershell脚本。

我已经阅读了这篇文章,其中介绍了如何运行输入到管道中的Powershell脚本,但我无法从文件运行脚本。

我尝试过:

powershell returnStatus: true, script: '-File build.ps1'

我尝试过各种组合,但是不知道如何做到这一点。

2个回答

29

很快就想通了,这行应该是这样的:

powershell returnStatus: true, script: '.\\build.ps1'

如何通过这种方式向 PowerShell 脚本传递参数? - starscream_disco_party
2
我认为你不应该从管道传递参数到脚本中,而是通过环境变量在脚本中访问变量。 - bic
你如何在Jenkins中设置环境变量以供PowerShell使用?@bic - Dugini Vijay
@bic - 在调用PowerShell时,作用域中的所有Jenkins环境变量都可以在PowerShell作用域中作为环境变量使用。这包括Jenkins默认的环境变量,如BUILD_NUMBER等,以及在此之前设置的任何内容。请记住我在下面的答案中提到的环境变量作用域规则。 - Max Cascone

3

@bic的答案非常好,对我很有帮助。如果您需要传递变量,而不想在脚本内使用环境变量,我发现最好的方法是两行代码(声明式语法):

writeFile file: 'tempFile.ps1', text: "${libraryResource 'psScript1.ps1'}"
powershell './tempFile.ps1 -someArg $env:someArg'

所以你正在将脚本内容写入本地目录的临时文件。然后你直接使用powershell调用脚本,并在调用中注入变量。

我同意在脚本中使用环境变量更方便。但需要注意以下几点模式:

  1. Env vars set in the top-level environment block can't be changed during the run. (At least that is my experience.)
  2. Env vars can only be Strings. There are tricks you can play to get maps to work, but they're tricks.
  3. 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'
           }
         }
       }
      ...
    
  4. 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 {
        ...
      }
    }
    

这是我发现的关于Jenkins环境变量的最佳参考资料:https://e.printstacktrace.blog/jenkins-pipeline-environment-variables-the-definitive-guide/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接