是否可以在管道常规脚本中直接调用PowerShell命令?在Jenkins中使用自定义作业时,我可以使用PowerShell插件调用该命令。但是在groovy脚本中没有片段可以使用它。
我也尝试了sh()
,但似乎此命令不允许命令内包含多行和注释。
最佳答案
要从Groovy脚本调用PowerShell脚本,请执行以下操作:
bat
命令。 errorlevel
)变量(EXIT 1
应导致FAILED
作业)。 $LastExitCode
。 Since Jenkins 2.207 with Powershell plugin 1.4, I have replace all my calls with the official powershell pipeline command. I do now recommend to use it.
对于那个波峰,我写了一些时髦的方法,可以将其集成到任何管道脚本中:
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一起使用效果很好。
[编辑]我添加了'%'掩码[/编辑]
然后,您可以在管道脚本中像这样调用脚本:
stage ('Call Powershell Script')
{
node ('MyWindowsSlave') {
PowerShell(". '.\\disk-usage.ps1'")
}
}
该方法的最好之处在于,您可以调用
CmdLet
,而不必在脚本中执行此操作(这是最佳实践)。调用ps1定义
CmdLet
,然后调用CmdLet
PowerShell(". '.\\disk-usage.ps1'; du -Verbose")
.
延迟脚本,以确保当脚本返回错误代码时,您的步骤失败(应该首选),如果您不在乎,请使用&
。 关于powershell - 直接在jenkins管道中执行powershell命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42436370/