【问题标题】:Invoke-RestMethod : The operation has timed outInvoke-RestMethod : 操作已超时
【发布时间】:2018-06-01 17:40:24
【问题描述】:

我有一个删除资源并创建新资源的脚本。时不时会超时,我不知道为什么。当我多次运行脚本时似乎会发生这种情况,但我无法获得明确的模式。我发现我的服务器还没有收到消息,因为还没有记录请求。

$old_values = Invoke-RestMethod -Uri $uri -Method Get

foreach($old_value in $old_values.result) {
    Invoke-RestMethod -Uri "$uri&key=$old_value.id" -Method Delete
}

$new_value = Invoke-RestMethod -Uri "$uri" -Body "{}" -ContentType application/json -Method Post

有趣的是,当我直接从 powershell 运行 Invoke-RestMethod 调用时,我偶尔会遇到超时。我还用 Fiddler 运行它们,并且从来没有超时。

[编辑] 我一直在检查与 netstat 的连接。当命令挂起时,它们被列为 ESTABLISHED。但我一直看到列出到我的服务器的 TIME_WAIT 连接。我的连接是否有可能没有关闭?

【问题讨论】:

标签: http powershell


【解决方案1】:

上面发布的 David Brabant 链接包含为我解决问题的解决方法:

$r = (Invoke-WebRequest -Uri $uri `
    -Method 'POST' `
    -ContentType 'application/json' `
    -Body '{}' `
    ).Content | ConvertFrom-Json

【讨论】:

  • 此错误已在 Powershell 5.0 中修复
【解决方案2】:

我发现 Allanrbo 的答案在 3 或 4 次运行后仍然超时。

我做了以下代替:

powershell "(Invoke-RestMethod -Method 'Delete' -Uri '$uri').Content"

【讨论】:

    【解决方案3】:

    很抱歉提出老话题。我们现在使用的是 Win 7 和 PowerShell 3.0 版 我们在使用 POST 方法时遇到了同样的问题。当我们第三次发布相同的 JSON 时,powershell 窗口将挂起。关闭并重新打开后它将起作用。

    要绕过它,只需在 POST 末尾添加 2 行:

    $ServicePoint = [System.Net.ServicePointManager]::FindServicePoint('<URL>')
    $ServicePoint.CloseConnectionGroup("")
    

    参考: https://social.technet.microsoft.com/wiki/contents/articles/29863.powershell-rest-api-invoke-restmethod-gotcha.aspx

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多