[英]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>&1
將stderr重定向到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
變量是一個字符串數組。$stderr
變量是一個ErrorRecord
數組。-like
運算符充當過濾器,它只輸出匹配的元素。 如果有任何匹配的元素,結果將轉換為$true
,否則它會在 boolean 上下文中轉換為$false
。-like
在使用類似字符串比較運算符時自動將ErrorRecord
轉換為string
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.