PowerShell调用Microsoft Graph API使用$filter无返回结果问题咨询
问题排查与修复方案
1. 核心问题:PowerShell 双引号变量展开冲突
你当前将请求URL放在双引号中,PowerShell会自动解析字符串内以$开头的内容为本地变量,你未提前定义$filter变量,最终发送的请求中过滤参数实际缺失/格式错误,自然无法返回匹配结果。
修复方案二选一:
- 方案1:用单引号包裹URL,避免PowerShell解析变量:
$GrapRisk = 'https://graph.microsoft.com/beta/identityProtection/riskyUsers?$filter=riskLevel eq microsoft.graph.riskLevel"medium"' - 方案2:用反引号(PowerShell转义符)转义
$符号:$GrapRisk = "https://graph.microsoft.com/beta/identityProtection/riskyUsers?`$filter=riskLevel eq microsoft.graph.riskLevel'medium'"
2. 结果返回不全问题处理
MS Graph API 默认开启分页限制,单次请求最多返回100条数据,如需获取全量列表,需要循环请求返回结果中的@odata.nextLink地址,直到无下一页标识为止,参考实现逻辑:
$ApplicationID = "45xxxxxxxx" $TenatDomainName = "2a3xxxxx" $AccessSecret = Read-Host "Enter Secret" $Body = @{ Grant_Type = "client_credentials" Scope = "https://graph.microsoft.com/.default" client_Id = $ApplicationID Client_Secret = $AccessSecret } $ConnectGraph = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenatDomainName/oauth2/v2.0/token" -Method POST -Body $Body $token = $ConnectGraph.access_token $allRiskyUsers = @() # 这里使用转义后的$filter $currentUri = "https://graph.microsoft.com/beta/identityProtection/riskyUsers?`$filter=riskLevel eq microsoft.graph.riskLevel'medium'" do { $response = Invoke-RestMethod -Headers @{Authorization = "Bearer $($token)"} -Uri $currentUri -Method Get $allRiskyUsers += $response.value $currentUri = $response.'@odata.nextLink' } while ($currentUri) $riskyList = $allRiskyUsers | Select-Object userPrincipalName, riskState, riskLastUpdatedDateTime, riskLevel $riskyList
额外排查建议
- 执行请求前先打印
$GrapRisk变量,确认生成的URL中是否包含完整的$filter=参数段 - 调用
Invoke-RestMethod时添加-Verbose参数,可查看实际发出的请求明细,快速定位参数异常 - 确认应用注册已授予
IdentityRiskyUser.Read.All类的应用权限,且已完成管理员同意
内容的提问来源于stack exchange,提问作者allyourbvse
相关产品推荐
相关产品推荐

