PowerShell, Invoke-RestMethod Error !

When running the PS Invoke-RestMethod, I got the connection closed Error ?

Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a send.

image

Looking on the net there are a lot’s simular posts coming up, providing solutions that had to do with avoiding certificates validation checks when running the script ?

like adding this to the script :

add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy : ICertificatePolicy {
        public bool CheckValidationResult(
            ServicePoint srvPoint, X509Certificate certificate,
            WebRequest request, int certificateProblem) {
            return true;
        }
    }
"@

[System.Net.ServicePointManager]::CertificatePolicy = ´
                        New-Object TrustAllCertsPolicy

Or

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

But, none of them worked out well?

So the solution is here :

When specifying an URI for the Invoke-RestMethode, don’t pre-fix it with HTTP:// or HTTPS://

Example :

Invoke-RestMethod -Uri "gdata.youtube.com/feeds/api/videos?v=2&q=PowerShell" `
| Select-Object Title, Author, Link

Result :

image

As simple as that Winking smile

Advertisements

3 Responses to PowerShell, Invoke-RestMethod Error !

  1. Ryan says:

    I’m having a similar issue but I see that with your example you say not to prefix the URI with http:// or https:// but in your example snippet you do. Trying without http:// or https:// gets the response “The URI prefix is not recognized”. Am I misunderstanding?

  2. @Ryan

    Sorry my mistake I posted a wrong example. corrected now.

    PS : if the solution does not work try adding the correct contenttype.

    Like this :
    Invoke-RestMethod -Method GET -ContentType “application/xml” -uri ….

  3. Ryan says:

    Ok, I am able to get responses the majority of the time but I intermittently (maybe 20% of the time) get the same “The underlying connection was closed: An unexpected error occurred on a send.” error. I may have to look into doing an Invoke-WebRequest instead.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: