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

PowerShell调用Google Forms API读取响应遇权限问题,求读取多选项方案

Google Forms API 数据读取的 PowerShell 实现建议

一、先解决授权问题

Google Forms API 强制要求 OAuth 2.0 授权,无授权的 GET 请求必然触发权限错误,按以下步骤处理:

  • 登录 Google Cloud Console,创建项目并启用 Forms API;创建「桌面应用」类型的 OAuth 客户端 ID,保存客户端 ID 和密钥。
  • 推荐使用官方 PowerShell 模块简化授权流程:
    1. 安装模块:Install-Module -Name Google.Apis.Forms.v1
    2. 获取授权令牌:
      $clientId = "你的客户端ID"
      $clientSecret = "你的客户端密钥"
      $scopes = @("https://www.googleapis.com/auth/forms.responses.readonly")
      $credential = Get-GoogleOAuthAccessToken -ClientId $clientId -ClientSecret $clientSecret -Scopes $scopes
      
  • 注意:即使表单是公开的,读取响应仍需表单所有者授权,确保授权账号拥有表单的「查看响应」权限。

二、解析响应中的答案字段

接口返回的 answers 是键值对结构,键为 questionId,值对应不同题型的答案数据。针对你的需求:

  1. 填空/单选题:提取 textAnswers 或 choiceAnswers 的单个值
  2. 第三页的16个勾选选项:属于多选题,对应 choiceAnswers 下的数组,需遍历取出所有勾选值

示例代码

$formId = "你的表单ID"
$accessToken = $credential.AccessToken
$apiUrl = "https://forms.googleapis.com/v1/$formId/responses"

# 发起授权请求获取响应数据
$response = Invoke-RestMethod -Uri $apiUrl -Headers @{Authorization = "Bearer $accessToken"}

# 遍历每条响应解析答案
foreach ($resp in $response.responses) {
    Write-Host "响应ID: $($resp.responseId)"
    Write-Host "最后提交时间: $($resp.lastSubmittedTime)"
    
    foreach ($answerItem in $resp.answers.PSObject.Properties) {
        $questionId = $answerItem.Name
        $answerContent = $answerItem.Value

        # 处理填空题/单选题
        if ($answerContent.PSObject.Properties.Name -contains "textAnswers") {
            $answerText = $answerContent.textAnswers.answers[0].value
            Write-Host "问题[$questionId] 答案: $answerText"
        }
        # 处理多选题(第三页的16个勾选选项)
        elseif ($answerContent.PSObject.Properties.Name -contains "choiceAnswers") {
            $selectedOptions = $answerContent.choiceAnswers.answers | ForEach-Object { $_.value }
            $optionsText = $selectedOptions -join " | "
            Write-Host "问题[$questionId] 勾选选项: $optionsText"
        }
    }
    Write-Host "-------------------------"
}

三、常见问题排查

  • 确认 Google Cloud Console 中已启用 Forms API,否则会返回「API 未启用」错误
  • 授权 scope 必须包含 https://www.googleapis.com/auth/forms.responses.readonly(只读响应权限)
  • 若为团队协作表单,确保授权账号被添加为表单的协作者并拥有「查看响应」权限
  • 第三页的16个选项属于同一个 questionId,解析时会在 choiceAnswers.answers 数组中返回所有勾选值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 05:37:42