powershell - REST API失败:Invoke-WebRequest:404

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

下面的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

编辑:

Google App脚本代码:
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)
}

最佳答案

  • 您可以确认用于写入和读取Google表格值的脚本可以正常工作。
  • 您只想修改用于使用Apps Script API运行Google Apps脚本的脚本。
  • 您已经可以使用Apps Script API。
  • 您的访问 token 可用于运行Google Apps脚本。
  • 您想使用powershell的Invoke-WebRequest实现此目的。

  • 如果我的理解是正确的,那么这个答案呢?请认为这只是几个可能的答案之一。

    修改要点:
  • 从您的错误消息和脚本中,我想提出以下修改要点。
  • "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/。这是不完整的端点。
  • 我认为您当前错误消息的原因是由于此。
  • 请在请求 header 使用访问 token ,而不要使用查询参数。 Ref
  • 我认为使用Sheets API也可以这样说。
  • 我认为"attempt" string"attempt"
  • 请将修改为"

  • 修改后的脚本:

    修改脚本中对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}"}
    

    注意:
  • 在我的环境中,我可以确认上面修改的脚本可以正常工作。遗憾的是,我无法理解您设置使用Google Apps Script API运行Google Apps脚本的流程。因此,如果在您的环境中发生错误,请再次确认使用Apps Script API运行脚本的设置。
  • 我认为"Bearer ${accessToken}"也可以修改为"Bearer $accessToken"

  • 引用:
  • Executing Functions using the Apps Script API

  • 如果我误解了您的问题,而这不是您问题的直接解决方案,我深表歉意。

    关于powershell - REST API失败:Invoke-WebRequest:404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60942605/

    相关文章:

    powershell - 如何使用 Start-Process 在 session 中使用本地 PowerShell 变量?

    javascript - 用于匹配包含 URL 的字符串中的字母数字的正则表达式

    javascript - JS 脚本可以阻塞整个服务器吗?如果是这样,我怎样才能摆脱这种攻击呢?

    php - Magento 管理屏幕添加新的审核按钮不起作用并生成 404 错误

    php - 尝试访问本地 LAMP 服务器上的 localhost 时出现 404 Not Found 错误

    Powershell 匹配行列表中的精确字符串

    powershell - powershell:从字符串末尾删除文本

    azure - 如何使用Powershell连接到本地Azure存储模拟器?

    google-apps-script - getRangeByName 停止工作!文档损坏或已知问题?

    javascript - 使用属性存储;添加到信息数组,检索信息