Thursday, April 28, 2011

Receiving (401) Unauthorized when accessing SharePoint server using webclient

I was trying to build a quick script to check on the status of a bunch of SharePoint servers. This is the code I was using:


$webclient = New-Object System.Net.WebClient
$webclient.Headers.Add("user-agent", "Powershell webclient")
$webclient.Credentials = New-Object System.Net.NetworkCredential("usernam", "password", "domain")
$webclient.DownloadString("http://MySharePointServer.com")

However, this is the error I got:

Exception calling "DownloadString" with "1" argument(s): "The remote server returned an error: (401) Unauthorized."
At line:1 char:26
+ $webclient.DownloadString <<<< ("http://MySharePointServer.com")
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

I searched high and low but found nothing useful. Then out of the blue I thought I would try


$webclient.DownloadString("http://MySharePointServer.com/default.aspx")


and lo and behold, the page loaded. I guess there must be something going on where webclient does not handle the default document or something to do with how I setup my SharePoint site. I don't have time to dig deeper into the root cause, but problem solved, moving on.

1 comment:

  1. Hello,

    I tried everything and your method with full url but it did not work out.

    BR,
    Dmytri
    (ddobei@nearcoders.com)

    ReplyDelete