【问题标题】:REST API failure: Invoke-WebRequest : 404REST API 失败:Invoke-WebRequest:404
【发布时间】:2020-07-11 12:48:13
【问题描述】:

下面的 Powershell 代码向 Google 表格写入和读取值(工作正常),应该使用 API 在 Apps 脚本项目中运行函数 myfunction,但 Invoke-WebRequest 返回以下错误:

Invoke-WebRequest : 404. That’s an error. The requested URL /v1/scripts/=ya29.a0Ae4lvC3k8aahOCPBgf-tRf4SRFxdcCE97fkbXLAJqZ4zRCLnBp9prwEcBYBAf
lYP6zyW3fLeD3u4iSw5jYtDAdgZiSsTjzQbCpj9e_ahCA0xwC_1NBTjYkPwqFdLli7LNpfFcuedFDhdUpfnKTRZdbBWIf2ZyxyuGc6p was not found on this server. That’s 
all we know.
No C:\Users\F76254C\Desktop\Nova pasta\Batch files\Available Projects\Latam HIL Lab Menu\libs\Google\WriteToGoogleSheets.ps1:64 caractere:13
+     $resp = Invoke-WebRequest -Uri "https://script.googleapis.com/v1/ ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

我不确定请求正文的 JSON 表示是否设置正确,或者错误是否是由其他原因引起的。

Powershell 代码:

function doit{
    $json = ".\client_id.json"
    $jdata = get-content $json | convertfrom-json
    <#
    $jdata | ForEach-Object {
        $_.PSObject.Properties.Value
    }
    #>
    $ClientID = $jdata.web.client_id.ToString()
    $ClientSecret = $jdata.web.client_secret.ToString()
    $refreshToken = "1//04VvG_FTyDGhiCgYIARAAGAQSNwF-L9IrZ-o1kaZQQccvzL5m4TUTNz6b9Q4KCb16t4cH11gGCshWZWvgaCoMlg73FgpLAGOYTEk" 
    $grantType = "refresh_token" 
    $requestUri = "https://accounts.google.com/o/oauth2/token" 
    $GAuthBody = "refresh_token=$refreshToken&client_id=$ClientID&client_secret=$ClientSecret&grant_type=$grantType" 
    $GAuthResponse = Invoke-RestMethod -Method Post -Uri $requestUri -ContentType "application/x-www-form-urlencoded" -Body $GAuthBody


    $accessToken = $GAuthResponse.access_token

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

                  "Content-type" = "application/json"}

    $DocumentID = "1htbeGlqZ4hojQBWl9fxE4nW_KZI9uVwi0ApzNOIbwnY"

    $currentDate = (Get-Date).ToString('MM/dd/yyyy')
    $currentTime = (Get-Date).ToString('HH:mm:sstt')

$json = @”
{
    "range": "HIL_APP!A1:G1",
    "majorDimension": "ROWS",
    "values":
                [[
                    "HIL_NAME",
                    "$env:ComputerName",
                    "$currentDate",
                    "$currentTime",
                    "$env:UserName",
                    "input from user",
                    "attempt"
                ],]
}
“@

    $write = Invoke-WebRequest -Uri "https://sheets.googleapis.com/v4/spreadsheets/$DocumentID/values/HIL_APP!A1:G1:append?valueInputOption=USER_ENTERED&access_token=$($accessToken)" -Method Post -ContentType "application/json" -Body $json
    $read = Invoke-WebRequest -Uri "https://sheets.googleapis.com/v4/spreadsheets/$DocumentID/values/HIL_APP!A1:G1?access_token=$($accessToken)"
    Write-Output "Response: " ($read.Content | ConvertFrom-Json)

$scriptId = "1eF7ZaHH-pw2-AjnRVhOgnDxBUpfr0wALk1dVFg7B220bg_KuwVudbALh"

$json = @”
{
  "function": "myfunction",
  "parameters": [
    "attempt" string
  ],
  "devMode": true
}
“@

    $resp = Invoke-WebRequest -Uri "https://script.googleapis.com/v1/scripts/$scriptId:run?access_token=$($accessToken)" -Method Post -ContentType "application/json" -Body $json
#    Write-Output "Response: " ($resp.Content | ConvertFrom-Json)
}

clear

doit

编辑:

谷歌应用脚​​本代码:

function toSpreadsheet(text2write)
  {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("HIL_APP");

  for (var i = 1; i < sheet.getLastRow(); i++)
  {
    sheet.getRange(i+1, 8, 1).setValue(text2write)
  }
  return "myreturn"
}

function myfunction(params)
{
  toSpreadsheet(params)
}

【问题讨论】:

    标签: powershell google-apps-script http-status-code-404 google-apps-script-api invoke-webrequest


    【解决方案1】:
    • 您可以确认用于写入和读取 Google 表格值的脚本工作正常。
    • 您只想修改使用 Apps Script API 运行 Google Apps 脚本的脚本。
      • 您已经能够使用 Apps Script API。
      • 您的访问令牌可用于运行 Google Apps 脚本。
    • 您想使用Invoke-WebRequest 的powershell 来实现这一点。

    修改点:

    • 根据您的错误信息和脚本,我想提出以下修改点。
      1. "https://script.googleapis.com/v1/scripts/$scriptId:run?access_token=$($accessToken)""https://script.googleapis.com/v1/scripts/${scriptId}:run"
        • 在您的脚本中,端点是https://script.googleapis.com/v1/scripts/。这是不完整的端点。
        • 我认为您当前错误消息的原因是由于此。
      2. 请在请求头使用访问令牌而不是查询参数。 Ref
        • 我认为使用 Sheets API 也可以这么说。
      3. 我认为"attempt" string"attempt"
      4. 请将修改为"

    修改脚本:

    当你的脚本中对 Apps Script API 的请求被修改后,变成如下。

    $scriptId = "1eF7ZaHH-pw2-AjnRVhOgnDxBUpfr0wALk1dVFg7B220bg_KuwVudbALh"
    
    $json = @"
    {
      "function": "myfunction",
      "parameters": ["attempt"],
      "devMode": true
    }
    "@
    
    $resp = Invoke-WebRequest -Uri "https://script.googleapis.com/v1/scripts/${scriptId}:run" -Method Post -ContentType "application/json" -Body $json -Headers @{"Authorization"="Bearer ${accessToken}"}
    

    注意:

    • 在我的环境中,我可以确认上述修改后的脚本有效。不幸的是,我无法理解您设置使用 Apps Script API 运行 Google Apps 脚本的流程。因此,如果在您的环境中发生错误,请再次确认使用 Apps Script API 运行脚本的设置。
    • 我觉得"Bearer ${accessToken}"也可以修改成"Bearer $accessToken"

    参考:

    【讨论】:

    • 我做了您建议的更改,之前我的代码被部署为 Web App,但现在它被部署为 API Executable,所以我停止收到错误,但仍然无法正常工作。谷歌脚本项目上的函数myfunction 没有触发我的Powershell 代码。 Google Script 上的函数myfunction 应该写入Google Sheet 而它不会,但是当我直接在Google App Script Dashboard 上运行它时它确实有效。我已经插入了范围 [link]googleapis.com/auth/spreadsheetsComments[link],在我看来只有这个范围就足够了
    • @Cleber Marques 感谢您的回复。很遗憾,从您的回复和提问中,我无法了解您的详细情况。这是因为我的技术不好。我对此深表歉意。我认为,首先,为了确认您对 Apps Script API 的设置,使用简单的 Google Apps Script 进行测试如何?因为您的问题是使用 Apps Script API 运行该函数。例如,function myFunction() {return "ok"}。当返回ok时,说明你的设置是正确的。这个怎么样?
    • 您的建议很棒!我已经做到了并且工作正常。这意味着powershell和GAS之间的通信很好。我已经创建了另一个帖子来讨论写电子表格的问题,所以每个人都可以从那里关注链接:stackoverflow.com/questions/61049670/…
    • @Cleber Marques 感谢您的回复。很高兴您可以使用 Apps Script API。我想想想你的新问题。
    猜你喜欢
    • 2016-07-15
    • 2021-07-22
    • 1970-01-01
    • 2018-07-19
    • 1970-01-01
    • 1970-01-01
    • 2017-03-19
    • 2017-05-27
    相关资源
    最近更新 更多