![](/img/trans.png)
[英]Jenkins Pipeline MissingPropertyException for Working Powershell Command
[英]Executing powershell command directly in jenkins pipeline
是否可以直接在管道 groovy 腳本中調用 PowerShell 命令? 在 Jenkins 中使用自定義作業時,我可以使用 PowerShell 插件調用命令。 但是在 groovy 腳本中沒有使用它的代碼段。
我也試過sh()
但似乎這個命令不允許命令內有多行和注釋。
從 Groovy-Script 調用 PowerShell 腳本:
bat
命令。errorlevel
) 變量將被正確返回( EXIT 1
應導致作業FAILED
)。$LastExitCode
。從 Jenkins 2.207 和 Powershell 插件 1.4 開始,我已經用官方的 powershell 管道命令替換了我所有的調用。 我現在建議使用它。 請注意,您必須預先確定
\\$ErrorActionPreference='Stop';
如果您希望腳本由於powershell 插件的問題而在寫入錯誤時中止,請添加到您的腳本中。
對於那個海豚,我編寫了一個小方法,可以集成到任何管道腳本中:
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 輸出編碼:適用於 Server 2016 和 Win10。[/EDIT] [EDIT] 我添加了 '%' 掩碼[/EDIT]
在你的流水線腳本中,你可以像這樣調用你的腳本:
stage ('Call Powershell Script')
{
node ('MyWindowsSlave') {
PowerShell(". '.\\disk-usage.ps1'")
}
}
該方法的最佳之處在於您可以調用CmdLet
而無需在腳本中執行此操作,這是最佳實踐。
調用 ps1 定義CmdLet
,然后調用CmdLet
PowerShell(". '.\\disk-usage.ps1'; du -Verbose")
.
為確保當腳本返回錯誤代碼時您的步驟失敗(應該是首選),如果您不關心它,請使用&
。正如Jenkins 博客中所宣布的那樣,現在通過powershell
步驟支持調用 PowerShell 腳本。
文檔提到它支持多行腳本。
從 Pipeline Nodes and Processes Plugin 2.28 版本開始,我們可以直接使用“powershell”。
Eg: powershell(". '.Test.ps1'")
您可以像這樣使用sh
命令:
sh """
echo 'foo'
# bar
echo 'hello'
"""
這里支持評論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.