You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell调用Graph API查询指定用户失败,返回全部用户问题求助

问题原因及解决办法

核心问题

你代码里的$filter在PowerShell双引号字符串中没有转义,导致PowerShell将$filter视为变量(若未定义则为空),最终生成的URL参数无效,Graph API忽略了过滤条件,返回默认的前100用户列表。另外,URL中直接使用单引号包裹UPN可能存在编码问题,也是潜在诱因。

修正方案

方案1:转义$filter的$符号(最直接)

在双引号字符串中,用反引号()转义$filter里的$`,避免PowerShell解析为变量,同时保留单引号的使用:

$upn = "example@example.com"
# 给$filter的$加反引号转义
$URL = "https://graph.microsoft.com/v1.0/users?`$filter=mail eq '$upn'"

Invoke-RestMethod -Method GET -Uri $URL -Headers $headers

方案2:使用URL编码处理UPN(更可靠,适配特殊字符)

当UPN包含特殊字符时,手动编码容易出错,用[Uri]::EscapeDataString()自动编码:

$upn = "example@example.com"
$encodedUpn = [Uri]::EscapeDataString($upn)
$URL = "https://graph.microsoft.com/v1.0/users?`$filter=mail eq '$encodedUpn'"

Invoke-RestMethod -Method GET -Uri $URL -Headers $headers

方案3:用双引号包裹UPN并转义

在PowerShell双引号字符串中,用两个双引号转义内部双引号,替代单引号:

$upn = "example@example.com"
$URL = "https://graph.microsoft.com/v1.0/users?`$filter=mail eq ""$upn"""

Invoke-RestMethod -Method GET -Uri $URL -Headers $headers

验证步骤

  1. 执行代码前先输出$URL,确认生成的URL格式正确,例如:
    https://graph.microsoft.com/v1.0/users?$filter=mail eq 'example@example.com'
    
  2. 确认$headers中的身份令牌有效,且服务主体的User.ReadWrite.All权限已正确授予并生效。

内容的提问来源于stack exchange,提问作者Emanuele

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 06:32:13