天天看點

Jenkins: 執行 PowerShell 指令安裝 PowerShell 插件在 build step 中執行 PowerShell 指令讓 build step 失敗Run task as admin在 pipeline 中執行 PowerShell 指令

Jenkins 預設是不支援執行 PowerShell 指令的,需要安裝插件才能完成這樣的任務。本文将介紹 Jenkins PoserShell 插件的基本用法和常見問題。

在 Jenkins->Plugin Manager 界面中選擇 "Available" 标簽頁,輸入 "powershell" 進行過濾:

Jenkins: 執行 PowerShell 指令安裝 PowerShell 插件在 build step 中執行 PowerShell 指令讓 build step 失敗Run task as admin在 pipeline 中執行 PowerShell 指令

選則 "PowerShell plugin",然後點選 "Install without restart" 按鈕。安裝完成後就可添加 PowerShell 類型的 build step 了:

Jenkins: 執行 PowerShell 指令安裝 PowerShell 插件在 build step 中執行 PowerShell 指令讓 build step 失敗Run task as admin在 pipeline 中執行 PowerShell 指令

我們通過 PowerShell 來執行一個簡單的任務:檢查 agent 的作業系統版本和 PowerShell 版本。

先建立一個 Freestyle 類型的 job,然後添加一個 "Windows PowerShell" 類型的 build step,并添加下面的 PowerShell 指令:

看起來像這個樣子:

Jenkins: 執行 PowerShell 指令安裝 PowerShell 插件在 build step 中執行 PowerShell 指令讓 build step 失敗Run task as admin在 pipeline 中執行 PowerShell 指令

儲存 job,然後運作它。執行成功後檢視運作日志:

Jenkins: 執行 PowerShell 指令安裝 PowerShell 插件在 build step 中執行 PowerShell 指令讓 build step 失敗Run task as admin在 pipeline 中執行 PowerShell 指令

上圖中的第一行說明了 Jenkins 是如何執行 PowerShell 指令的,其實就是把我們寫的指令打包到一個 PowerShell 腳本檔案中,然後在 agent 上調用 powershell.exe 執行這個腳本。第二個和第三個紅框中則是輸出的系統版本和 PowerShell 版本資訊。

接下來我們發現,無論怎麼執行 PowerShell 指令,build step 的結束狀态都是 "成功"(包括一些指令執行失敗的情況)!

Jenkins: 執行 PowerShell 指令安裝 PowerShell 插件在 build step 中執行 PowerShell 指令讓 build step 失敗Run task as admin在 pipeline 中執行 PowerShell 指令

這是不科學的,因為當指令執行失敗或是滿足一些條件時,我們希望 build step 的結束狀态是 "失敗"。後續的 build step 根據前面 step 的結束狀态決定是否執行。

預設情況下之是以 build step 不會失敗,是因為 PowerShell 執行的過程中沒有執行 exit 調用!這就導緻 Jenkins 無法判斷執行的指令是否成功退出,預設就認為都是成功的啦。是以要完善這裡的邏輯就要求我們一定要在腳本中實作自己的 exit 邏輯:判斷腳本執行成功時調用 exit 0;判斷腳本執行失敗時調用 exit 1(當然你可以根據自己的需要傳回其他整數)。

作為 demo,我們編輯上面的 job 并在最後一行添加 exit 1,儲存後執行:

Jenkins: 執行 PowerShell 指令安裝 PowerShell 插件在 build step 中執行 PowerShell 指令讓 build step 失敗Run task as admin在 pipeline 中執行 PowerShell 指令

終于可以讓 build step 失敗了!

在 Windows 類型的 agent 上執行的任務,有些需要 admin 權限。那麼如何以 admin 權限執行 PowerShell 的指令呢?其實這是由 Jenkins agent 程式運作的權限決定的。

我們在 agent 上啟動 Jenkins 程式的時候有大概三種選擇,直接運作或者以 run as admin 的方式運作再或者以 Windows Service 方式運作的。如果以後兩種方式運作 Jenkins agent 程式,那麼所有的 task 也會以 admin 的權限運作。

毫無疑問,pipeline 将會被越來越多的使用。我們當然應當具備在 pipeline 中執行 PowerShell 指令的能力。還好,Jenkins 剛剛支援了這個功能。建立一個 pipeline 類型的 job,輸入下面的代碼:

然後儲存并運作。遺憾的是,這個功能還不完美:

Jenkins: 執行 PowerShell 指令安裝 PowerShell 插件在 build step 中執行 PowerShell 指令讓 build step 失敗Run task as admin在 pipeline 中執行 PowerShell 指令

在筆者的環境中,輸出的日志總帶有一點亂碼,具體原因不明。猜測是 pipeline 功能對 PowerShell 插件的支援還有小問題。

本文轉自帥氣的頭頭部落格51CTO部落格,原文連結http://blog.51cto.com/12902932/1950345如需轉載請自行聯系原作者

sshpp

繼續閱讀