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

如何通过Microsoft Graph API和PowerShell获取指定SharePoint Online站点

解决通过Microsoft Graph API获取指定SharePoint Online站点ID的问题

问题描述

编写PowerShell脚本通过Microsoft Graph API获取指定SharePoint Online站点的SiteID,但API调用后返回所有站点,尝试$search、$filter组合均无效,已为应用注册配置所需权限。

完整原脚本

$siteUrl = "https://bernardcomms.sharepoint.com/sites/Project1"
$tenantId = "" 
$clientId = "" 
$clientSecret = "" 

# 获取Microsoft Graph API的访问令牌
$tokenAuthUri = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
$tokenRequestBody = @{
    grant_type = "client_credentials"
    client_id = $clientId
    client_secret = $clientSecret
    scope = "https://graph.microsoft.com/.default"
}
$tokenResponse = Invoke-RestMethod -Method Post -Uri $tokenAuthUri -Body $tokenRequestBody
$accessToken = $tokenResponse.access_token

# 获取SharePoint站点ID
$requesturi = "https://graph.microsoft.com/v1.0/sites?$search=$siteUrl"
$siteIdResponse = Invoke-RestMethod -Method Get -Uri $requesturi -Headers @{Authorization=("bearer {0}" -f $accessToken)}

$siteId = $siteIdResponse.value.id
$siteId

尝试过的请求URI

$requesturi = "https://graph.microsoft.com/v1.0/sites?$search=weburl eq '$siteUrl'"
$requesturi = "https://graph.microsoft.com/v1.0/sites?$filter=weburl eq '$siteUrl'"

已配置权限

应用注册已配置Sites.Read.All应用权限(已授予管理员同意)


解决方案

核心原因

Microsoft Graph API的sites集合不支持通过$filter=weburl eq ...过滤站点,$search也无法精准匹配站点URL,正确做法是使用站点URL直接寻址的API格式。

正确的API调用方式

使用GET /sites/{hostname}:/{server-relative-path}格式,直接通过站点URL的主机名和相对路径定位目标站点。

修改后的PowerShell脚本

$siteUrl = "https://bernardcomms.sharepoint.com/sites/Project1"
$tenantId = "" 
$clientId = "" 
$clientSecret = "" 

# 解析站点URL的主机名和相对路径
$siteUri = [Uri]$siteUrl
$hostname = $siteUri.Host
$relativePath = $siteUri.LocalPath.TrimStart('/')

# 获取Microsoft Graph API的访问令牌
$tokenAuthUri = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
$tokenRequestBody = @{
    grant_type = "client_credentials"
    client_id = $clientId
    client_secret = $clientSecret
    scope = "https://graph.microsoft.com/.default"
}
$tokenResponse = Invoke-RestMethod -Method Post -Uri $tokenAuthUri -Body $tokenRequestBody
$accessToken = $tokenResponse.access_token

# 获取指定站点的ID
$requesturi = "https://graph.microsoft.com/v1.0/sites/$hostname`:/$relativePath"
$siteResponse = Invoke-RestMethod -Method Get -Uri $requesturi -Headers @{Authorization=("bearer {0}" -f $accessToken)}

$siteId = $siteResponse.id
Write-Host "站点ID: $siteId"

说明

  1. 脚本通过[Uri]类解析站点URL,自动提取主机名和相对路径,适配不同格式的站点URL
  2. API请求URI中的:是Graph API寻址格式的固定分隔符,需在PowerShell中用反引号`转义
  3. 已配置的Sites.Read.All应用权限足够完成此操作,无需额外权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 11:31:00