PowerShell: The remote server returned an error: (403) Forbidden


if you are getting following errors in your powershell script while executing CSOM for sharepoint Online.






PS C:\Users\pullareddym> $ClientContext.ExecuteQuery()
Exception calling "ExecuteQuery" with "0" argument(s): "The remote server returned an error: (403) Forbidden."
At line:1 char:1
+ $ClientContext.ExecuteQuery()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : WebException

Reason:
You are missing the SharePoint Online Client Component SDK on your computer.




Solution:

1.       Download SharePoint Online Client Component SDK
Install and restart PowerShell. You should be able to connect to SharePoint online using CSOM.

2.       Add the following lines to your code.
Add-Type -path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll'
Add-Type -path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll'


  

Example code below updates site collection logo using powershell.
Add-Type -path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll'
Add-Type -path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll'

$user = "admin@spotent.sharepoint.onmicrosoft.com";
$pass = "Training202020";
$secpw = $pass | ConvertTo-SecureString -AsPlainText -Force

$ClientContext = New-Object Microsoft.SharePoint.Client.ClientContext("https://spotent.sharepoint.com/sites/sctest");
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($credential.UserName,$credential.Password);
$ClientContext.Credentials = $Creds;

$ClientContext.Web.SiteLogoUrl = "/SiteAssets/banner.jpg";
$ClientContext.Web.Update();
$ClientContext.ExecuteQuery();
$ClientContext.Dispose();





1 comment:

  1. why is SharePoint Online Client Component SDK is required to be installed

    ReplyDelete