Error: Exception calling “ExecuteQuery” with “0” argument(s): “The remote server returned an error: (403) Forbidden.” in PowerShell scripts for SharePoint Online.
Troubleshooting Checklist for 403 forbidden in SharePoint Online PowerShell:
Follow this checklist to resolve Executequery 403 forbidden error in SharePoint Online PowerShell:
- You may have provided the credentials of another tenant, which would end up with this error message (Happens when working with multiple tenants!) So make sure the URL and credentials are correct.
- You may be missing the SharePoint Online Client Component SDK on your client computer. Make sure you have the latest version installed and the referenced DLL paths are correct.
- You may be attempting to access a site that you don’t have access to! Verify your access to the site by browsing to it. Having Tenant Admin or SharePoint Online Administrator roles doesn’t gain your access to SharePoint sites automatically. You have to add yourself to the site explicitly: How to Add Site collection Administrator to SharePoint Online using PowerShell?
- The site may be in locked state! You can check the lock status and unlock: How to Lock/Unlock Sites in SharePoint Online?
- You may need to be in your organization network with a compliant device as per the conditional access policies of your tenant.
- The credential you pass must be of type “SharePointOnlineCredentials”. E.g.,
#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" #parameters $SiteURL = "https://Crescent.sharepoint.com" $UserName = "[email protected]" $Password = "Password goes here" $SecurePassword= $Password | ConvertTo-SecureString -AsPlainText -Force #Setup the Context $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL) $Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $SecurePassword) $Ctx.Credentials = $Cred #Get the Site Collection storage used $Site = $Ctx.Site $Ctx.Load($Site) $Site.Retrieve("Usage") $ctx.ExecuteQuery() $StorageUsed = [Math]::Round(($Site.Usage.Storage/1MB),2) #Get Site Collection Size Write-host "Storage Used: $StorageUsed MB"
- If you try to connect to the Tenant Admin site, make sure the Tenant Admin URL is: https://YourDomain-admin.sharepoint.com, The below script would give you an error: Get-PnPSite : The remote server returned an error: (403) Forbidden.
$TenantAdminURL = "https://crescent-admin.sharepoint.com/sites/london" #Connect to the Site Connect-PnPOnline -URL $TenantAdminURL -Interactive Get-PnPSite