chani
chani

Reputation: 803

Invoke-RestMethod : The operation has timed out

I have a script that deletes resources and creates new ones. Every now and then it times out and I can't figure out why. It seems to happen when I run the script multiple times, but I couldn't get a definite pattern. I found that my server hasn't picked up the message yet since there's no logging for the request yet.

$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

Interesting note, I get occasional timeouts when I run the Invoke-RestMethod calls directly from powershell. I also ran them with Fiddler and never got timeouts.

[Edit] I've been checking the connections with netstat. While the commands are hanging, they're listed as ESTABLISHED. But I keep seeing TIME_WAIT connections listed to my server. Is there a chance my connections aren't getting closed?

Upvotes: 6

Views: 6875

Answers (3)

Mark
Mark

Reputation: 323

Sorry to bring up old topic. We are using Win 7 now and PowerShell version 3.0 We encountered the same problem with POST method. When we POST the same JSON the 3rd time, powershell window will hang. After close and reopen it will work.

To get around it, simple add 2 lines at the end of POST:

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

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

Upvotes: 1

Jesse
Jesse

Reputation: 33

I found Allanrbo's answer to still timeout after 3 or 4 runs.

I did the following instead:

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

Upvotes: 0

Allanrbo
Allanrbo

Reputation: 2358

The link David Brabant posted above contains this workaround that solved the problem for me:

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

Upvotes: 5

Related Questions