SharePoint Online: “The remote server returned an error (401) Unauthorized” Error in PowerShell

Problem: Exception calling “ExecuteQuery” with “0” argument(s): “The remote server returned an error (401) Unauthorized.” Error in SharePoint Online PowerShell script.

The remote server returned an error: (401) Unauthorized.

Troubleshooting Checklist:

Here are the various root causes and solutions for this issue:

1. Is your URL Correct?

#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

#Set Variables
$SiteURL = "http://crescent.sharepoint.com/sites/marketing" 
 
#Get Credentials to connect
$Cred= Get-Credential
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
  
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = $Credentials
 
#Get the Web
$Web=$Ctx.Web
$Ctx.Load($Web)
$Ctx.ExecuteQuery()

You’ll get the same error “Connect-SPOService : The remote server returned an error: (401) Unauthorized.” if you try to connect using Connect-SPOService cmdlet.

Connect-SPOService -Url "http://crescent-admin.sharepoint.com" -Credential (Get-Credential)

Here in this script, the URL was incorrect! instead of “https://tenant.sharepoint.com”, it was “http://tenant.sharepoint.com”. The SharePoint Online URL must start with HTTPS always!

2. Do you have Permissions to the site?

If you don’t have permission to access the target site through a browser, you can’t access it from PowerShell too (absolutely!). So, check if you have sufficient permission and able to open the site in the web browser.

3. Legacy authentication protocol is enabled?

Check if the Legacy authentication protocol is enabled in your tenant.

Get-SOPTenant -LegacyAuthProtocolsEnabled

If not, enable it with:

Set-SOPTenant -LegacyAuthProtocolsEnabled $True 

Salaudeen Rajack

Information Technology Professional with Two decades of SharePoint Experience.

2 thoughts on “SharePoint Online: “The remote server returned an error (401) Unauthorized” Error in PowerShell

  • July 5, 2021 at 6:40 AM

    So do I: Error Generating Site Permission Report! Exception calling “ExecuteQuery” with “0” argument(s): “The remote server returned an error: (401) Unauthorized.”

    Reply
  • June 8, 2021 at 4:17 PM

    Hello, I still got the same error after executing the command.
    I’m getting The remote server returned an error (401) Unauthorized when trying to create a subsite using powershell CSOM and c# CSOM (Microsoft.SharepointOnline.CSOM)

    Reply

Leave a Reply