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

使用PowerShell调用Google Calendar API仅返回1条事件的问题

解决Google Calendar API仅返回1条事件的问题

嘿,我一眼就瞅出问题所在了!你把maxResults参数放错位置啦——Google Calendar API的这个参数是查询参数,得放在请求的URL参数里,而不是塞进请求头(Headers)里面。你之前的写法会让Authorization头变成一串混乱的内容,API根本识别不了这个参数,自然就用了默认的返回规则(大概率只返回最近的1条事件)。

第一步:修正参数位置

先给你一个基础的修正版本,把maxResults移到正确的位置:

$CalURL="https://www.googleapis.com/calendar/v3/calendars/primary/events"
$header=@{ Authorization = "Bearer $($tokens.access_token)" }
# 用QueryParameter传递maxResults参数,这才是正确的姿势
Invoke-RestMethod -Headers $header -Uri $CalURL -Method Get -ContentType 'application/json' -QueryParameter @{ maxResults = 2500 }

第二步:处理分页(可选但推荐)

虽然你说日历里只有40多条事件,2500的maxResults足够一次性获取,但如果之后事件数量超过这个值,API会返回nextPageToken,需要循环拉取所有分页内容。给你一个更健壮的版本:

$CalURL="https://www.googleapis.com/calendar/v3/calendars/primary/events"
$header=@{ Authorization = "Bearer $($tokens.access_token)" }
$allEvents = @()
$pageToken = $null

do {
    # 构建请求参数,包含当前页的pageToken(如果有的话)
    $requestParams = @{
        Headers = $header
        Uri = $CalURL
        Method = 'Get'
        ContentType = 'application/json'
        QueryParameter = @{ 
            maxResults = 2500
            pageToken = $pageToken
        }
    }
    # 发起请求
    $response = Invoke-RestMethod @requestParams
    # 把当前页的事件添加到总列表
    $allEvents += $response.items
    # 更新pageToken,准备拉取下一页
    $pageToken = $response.nextPageToken
} while ($pageToken) # 直到没有下一页为止

# 输出获取到的总事件数
Write-Host "成功获取到 $($allEvents.Count) 条日历事件"

这样修改后,你就能拿到所有40多条事件啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:26:03