直接在jenkins管道中执行powershell命令 [英] Executing powershell command directly in jenkins pipeline
问题描述
是否可以在管道常规脚本中直接调用PowerShell命令?在Jenkins中使用自定义作业时,我可以使用PowerShell插件调用该命令.但是在groovy脚本中没有片段可以使用.
Is it possible to call a PowerShell command directly in the pipelines groovy script? While using custom jobs in Jenkins I am able to call the command with the PowerShell Plugin. But there is no snippet to use this in the groovy script.
我也尝试过sh()
,但是似乎该命令不允许命令中包含多行和注释.
I also tried sh()
but it seems that this command does not allow multiple lines and comments inside the command.
推荐答案
要从Groovy脚本调用PowerShell脚本:
To call a PowerShell script from the Groovy-Script:
- 您必须使用
bat
命令. - 此后,您必须确保正确返回错误代码(
errorlevel
)变量(EXIT 1
应导致FAILED
作业). - 最后,要与PowerShell-Plugin兼容,您必须确保将考虑使用
$LastExitCode
. - 我注意到'powershell'现在可以在管道中使用,但是由于存在多个问题,因此我更喜欢此变体.仍在等待它稳定.实际上,我的"dontKillMe"行为存在问题.
- you have to use the
bat
command. - After that, you have to be sure that the Error Code (
errorlevel
) variable will be correctly returned (EXIT 1
should resulting in aFAILED
job). - Last, to be compatible with the PowerShell-Plugin, you have to be sure that
$LastExitCode
will be considered. - I have notice that the 'powershell' is now available in pipeline, but since it have several issues I prefer this variant. Still waiting it works stabil. I actually have an issue with the 'dontKillMe' behavior.
为此,我写了一些时髦的方法,可以将其集成到任何管道脚本中:
For that porpuse I have written a little groovy method which could be integrate in any pipeline-script:
def PowerShell(psCmd) {
psCmd=psCmd.replaceAll("%", "%%")
bat "powershell.exe -NonInteractive -ExecutionPolicy Bypass -Command \"\$ErrorActionPreference='Stop';[Console]::OutputEncoding=[System.Text.Encoding]::UTF8;$psCmd;EXIT \$global:LastExitCode\""
}
我添加了UTF8 OutputEncoding:与Server 2016和Win10一起使用非常好.[/EDIT] 我添加了'%'掩码[/EDIT]
然后,您可以在管道脚本中这样调用脚本:
In your Pipeline-Script you could then call your Script like this:
stage ('Call Powershell Script')
{
node ('MyWindowsSlave') {
PowerShell(". '.\\disk-usage.ps1'")
}
}
该方法的最好之处在于,您可以调用CmdLet
而不用在脚本中进行操作,这是最佳实践.
The best thing with that method, is that you may call CmdLet
without having to do this in the Script, which is best-praxis.
调用ps1定义CmdLet
,然后调用CmdLet
Call ps1 to define CmdLet
, an then call the CmdLet
PowerShell(". '.\\disk-usage.ps1'; du -Verbose")
- 别忘了使用 withEnv(),那么比完全兼容Powershell插件要好.
- 使用
.
推迟脚本,以确保当脚本返回错误代码时应该执行此步骤(应优先使用),如果您不关心它,请使用&
. - Do not forget to use withEnv() an then you are better than fully compatible with the Powershell plugin.
- postpone your Script with
.
to be sure your step failed when the script return an error code (should be preferred), use&
if you don't care about it.
这篇关于直接在jenkins管道中执行powershell命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!