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

使用PowerShell调用MS Graph API获取SPO站点失败求助

问题分析与解决

问题现象

通过PowerShell调用MS Graph API获取所有SharePoint Online站点时,返回结果为:

@{@odata.context=https://graph.microsoft.com/v1.0/$metadata#sites; value=System.Object[]}

所用应用已获得管理员同意的应用类型API权限(Sites.Read.All、Sites.ReadWrite.All),尝试过多个API URI均未成功获取站点名称和URL。

核心原因及解决办法

1. 输出方式错误,未访问实际数据集合

Invoke-RestMethod返回的是PSCustomObject对象,其中value属性才是存储站点数据的数组。直接用Write-Host $AllSites只会输出对象的字符串类型标识,而非实际的站点数据。

解决: 访问value属性并筛选需要的字段,示例:

# 格式化输出站点名称和URL
$AllSites.value | Select-Object name, webUrl | Format-Table -AutoSize
# 或导出到CSV文件
$AllSites.value | Select-Object name, webUrl | Export-Csv -Path "SPOSites.csv" -NoTypeInformation

2. API请求URI存在语法错误

你尝试的第三个URI缺少查询参数的起始分隔符?,导致参数无法被Graph API识别。原错误URI:

https://graph.microsoft.com/v1.0/sites$select=siteCollection,webUrl&$filter=siteCollection/root%20ne%20null

修正后:

https://graph.microsoft.com/v1.0/sites?$select=siteCollection,webUrl&$filter=siteCollection/root ne null

3. Token请求参数不符合client credentials流要求

使用旧Azure AD端点(oauth2/token)的client credentials模式时,scope参数设置为openid是错误的——该参数用于获取ID Token,不适用于资源访问的client credentials流,直接移除该参数即可,仅保留resource指定Graph API地址。

修正后的token请求body:

$body = @{
    'resource'      = 'https://graph.microsoft.com'
    'client_id'     = $ApplicationId
    'client_secret' = $ApplicationSecret
    'grant_type'    = "client_credentials"
}

4. 正确选择获取全量站点的API端点

要获取所有SPO站点,推荐使用带search=*的端点(需确保应用已拥有Sites.Read.All权限):

$AllSites = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/sites?search=*" -Headers $headers -Method Get

完整修正后的脚本

$TenantID = 'xxxxxxxxx.ONMICROSOFT.COM'
$ApplicationId = "xxxxx-xxxxxx-xxxx-xxxx"
$ApplicationSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

$body = @{
    'resource'      = 'https://graph.microsoft.com'
    'client_id'     = $ApplicationId
    'client_secret' = $ApplicationSecret
    'grant_type'    = "client_credentials"
}

$ClientToken = Invoke-RestMethod -Method post -Uri "https://login.microsoftonline.com/$($tenantid)/oauth2/token" -Body $body -ErrorAction Stop
$headers = @{ "Authorization" = "Bearer $($ClientToken.access_token)" }

# 调用API获取所有站点
$AllSites = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/sites?search=*" -Headers $headers -Method Get 

# 输出站点名称和URL
$AllSites.value | Select-Object name, webUrl | Format-Table -AutoSize

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 10:20:31