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

Marketo API分页数据获取异常:PowerShell脚本仅返回20条且报URI错误

修复Marketo API分页脚本并获取全部数据

原脚本存在两个核心问题导致无法正常分页:

  1. URI参数拼接错误:手动拼接多参数时未使用&分隔,导致后续请求的URI格式非法,触发Invalid URI: The hostname could not be parsed.报错。
  2. 分页逻辑不够严谨:手动计算分页参数易出错,且未利用API的最优配置提升效率。

以下是修复后的完整脚本:

$clientId = "************************************"
$clientSecret = "********************************"
$baseURL = "https://XXX-XXX-XXX.mktorest.com"

# 获取访问令牌
$tokenEndpoint = "$baseURL/identity/oauth/token"
$tokenRequestBody = @{
    grant_type    = "client_credentials"
    client_id     = $clientId
    client_secret = $clientSecret
}
$tokenResponse = Invoke-RestMethod -Uri $tokenEndpoint -Method Post -Body $tokenRequestBody
$accessToken = $tokenResponse.access_token

$endpoint = "$baseURL/rest/asset/v1/forms.json"
$pageSize = 200  # Marketo API最大支持单页200条数据,可减少请求次数
$offset = 0

do {
    $headers = @{
        Authorization = "Bearer $accessToken"
    }

    # 用-QueryParameter自动处理参数拼接与编码,彻底避免URI格式错误
    $response = Invoke-RestMethod -Uri $endpoint -Method Get -Headers $headers -QueryParameter @{
        offset     = $offset
        maxReturn  = $pageSize
    }

    if ($response.success) {
        # 输出当前页数据
        foreach ($form in $response.result) {
            Write-Output "Form ID: $($form.id), Name: $($form.name), Description: $($form.description)"
        }

        # 更新偏移量,准备下一页请求
        $offset += $pageSize
    } else {
        Write-Output "请求错误: $($response.errors -join '; ')"
        break
    }
} while ($response.moreResult)

关键修复说明:

  • 替换手动URI拼接:使用Invoke-RestMethod的-QueryParameter参数自动构建查询字符串,它会自动处理参数分隔符&和URL编码,彻底解决URI解析错误。
  • 优化分页效率:将pageSize设为API支持的最大值200,减少总请求次数;改用offset递增的方式,更贴合Marketo API的分页机制。
  • 简化代码逻辑:移除冗余的ContentType头(GET请求无需设置),简化布尔值判断逻辑。

额外优化建议:

  • 若运行中遇到令牌过期,可在循环内增加令牌有效性检查,过期时自动重新获取。
  • 如需持久化数据,可在循环内添加$response.result | Export-Csv -Path './marketo_forms.csv' -Append -NoTypeInformation将结果保存为CSV文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 15:46:10