Skip to content

Invoke-WebRequest and Invoke-RestMethod get (401) Unauthorized without any reason

I use PowerShell to access a lot of API’s! Since a while some calls that are correct get the error: “The remote server returned an error: (401) Unauthorized.“.
In my case, this was only the case when I used Windows PowerShell (e.g., PowerShell 5.x)! PowerShell Core (7.x) worked fine.

I took me a while and a lot of Fiddler sessions to find a header in some of the requests: “Expect: 100-continue“! I found this only in calls from Windows PowerShell (e.g., PowerShell 5.x). In general, this header is a good thing! But some API providers have issues with it.

That both Invoke-WebRequest and Invoke-RestMethod have the same behaviour make sense, both use “System.Net.HttpWebRequest“, which uses the namespace “System.Net.Http.Headers“.

Here is the error that I got from several API providers:

Exception : The remote server returned an error: (401) Unauthorized.
Reason    : WebException
Target    : System.Net.HttpWebRequest

Based on the docs that I found, the default value is true! Why ever I saw this Header in Windows PowerShell only! PowerShell Core (on any Plattform) never added this header. It is enabled by default on both.

Anyway, you can disable this header:

ServicePointManager.Expect100Continue = false;

In my case, I just added the following to my scripts and modules:

if ([Net.ServicePointManager]::Expect100Continue -ne $false)
{
   [Net.ServicePointManager]::Expect100Continue = $false
}

You can check if Expect100Continue is enabled (this the default):

[Net.ServicePointManager]::Expect100Continue
Published inPowerShell

Be First to Comment

    Leave a comment

    By posting a comment you consent that I store the submitted information as well as your anonymized IP address on my servers, under the terms of my Privacy Policy. Your email is never shared with anyone else.

    Required fields are marked *.