如何捕获Invoke-PowerBIRestMethod返回的DMTS_UserNotFoundInADGraphError错误
解决Invoke-PowerBIRestMethod无法捕获DMTS_UserNotFoundInADGraphError错误的问题
问题核心
调用Invoke-PowerBIRestMethod -Method Get时返回的DMTS_UserNotFoundInADGraphError属于非终止错误,默认不会触发try/catch块,因此直接编写的try/catch逻辑无法捕获该错误。该错误的消息结构如下:
Message : Encountered errors when invoking the command: { "code": "DMTS_UserNotFoundInADGraphError", "pbi.error": { "code": "DMTS_UserNotFoundInADGraphError", "parameters": {}, "details": [], "exceptionCulprit": 1 }
解决思路
要捕获这类非终止错误,必须在调用命令时添加-ErrorAction Stop参数,强制将非终止错误转换为终止错误,使其进入try/catch处理流程。之后通过匹配错误消息中的关键词识别特定错误,其他未匹配的错误则统一处理。
可行代码示例
try { # 添加-ErrorAction Stop,强制非终止错误转为终止错误以触发catch $Datasets = (Invoke-PowerBIRestMethod -Url $URL -Method Get -TimeoutSec 50000 -ErrorAction Stop | ConvertFrom-Json).value } catch [System.Exception]{ # 匹配错误消息中的特定错误码,执行对应逻辑 if ($_.Exception.Message -ilike "*DMTS_UserNotFoundInADGraphError*") { Write-Output "UserNotFound" # 也可自定义其他处理,比如: # $DatasourceType = "Entra用户已不存在,无有效工作区" } } catch{ # 处理所有未匹配的其他错误 Write-Output "New error - please investigate" # 如需输出详细错误信息,可添加: # Write-Host "数据集$datasetID出错,原因:$($_.FullyQualifiedErrorId)" }
原代码无效原因
你之前的代码未添加-ErrorAction Stop参数,DMTS_UserNotFoundInADGraphError作为非终止错误不会触发catch块,导致try块执行后错误被忽略,catch逻辑根本不会运行。
内容的提问来源于stack exchange,提问作者Tom Roberts
相关产品推荐
相关产品推荐

