Handling ExecuteQuery 403 Error in Powershell script

Copper Contributor

Hey everyone,


I am a rookie for PowerShell and currently working on a script to build up a connection from a CSV file to SharePoint list. I get this error below even it runs ExecuteQuery() when I have already included microsoft.sharepoint.client.dll and Microsoft.SharePoint.Client.Runtime.dll. 



Here is my code snippet, any input would help :) Thank you all


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'
#connect to Sharepoint
$credentials = Get-Credential -Message "Please Enter SharePoint Online credentials";
$Site = "https://xyz.sharepoint.com/";
Connect-PnPOnline -Url $Site -Credentials $credentials;
$listName = "test";

#import csv $csv=Import-CSV "C:\Users\LiLin-aretoconsultin\Desktop\powerapps\csv\test.csv";
#site contents access $cxt = New-Object Microsoft.SharePoint.Client.ClientContext($Site) $web = $cxt.Web $List =$web.Lists.GetByTitle($listName) $import = [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery() $item = $List.GetItems($import) $cxt.Load($web) $cxt.load($item) $cxt.ExecuteQuery() # <- this gives error


1 Reply

@manofiron068 Try modifying your script as follows. 


#site contents access
$cxt = New-Object Microsoft.SharePoint.Client.ClientContext($Site)

$cxt.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($credentials.UserName,$credentials.Password) #creds for the context to avoid 403 permissions error

$web = $cxt.Web