簡體   English   中英

如何捕獲錯誤錯誤:權限不足,無法完成操作。 在 Powershell Azure Devops 管道中

[英]How to trap Error ERROR: Insufficient privileges to complete the operation. in Powershell Azure Devops Pipeline

我創建了一個 Azure Devops 管道並創建了在 ServiceConnection 上下文中運行的 Powershell 腳本。 此服務連接是 Azure ServicePrincipal。

$groupName =  "ABC"
$res = (az ad group list --display-name $groupName)

Write-Host "Response " $res

當我執行管道時,我收到此錯誤消息

錯誤:權限不足,無法完成操作。

然而 $res 是 null。

我如何在我的 powershell 代碼中捕獲此錯誤消息?

看起來錯誤已寫入stderr ,因此如果您想檢查錯誤消息,請使用重定向運算符2>&1stderr重定向到stdout

$stdout, $stderr = (az ad group list --display-name $groupName 2>&1).Where({$_ -is [string]}, 'Split') 

if( $stderr -like '*Insufficient privileges to complete the operation*' ) {
   # Handle the error
}
  • 使用重定向運算符2>&1錯誤 stream(又名stderr )合並到成功 stream(又名stdout ),因此我們可以統一對待它們。
  • 使用組運算符(…) ,從流中創建一個臨時數組。
  • 使用內在.Where()方法,我們根據 stream 類型將這個數組分成兩個變量。
  • 如果有任何消息寫入stdout ,則$stdout變量是一個字符串數組。
  • 如果有任何消息寫入stderr ,則$stderr變量是一個ErrorRecord數組。
  • 當 LHS 參數是一個集合時, -like運算符充當過濾器,它只輸出匹配的元素。 如果有任何匹配的元素,結果將轉換為$true ,否則它會在 boolean 上下文中轉換為$false
  • -like在使用類似字符串比較運算符時自動將ErrorRecord轉換為string

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM