Powershell – How to connect to SharePoint 2013 on-premise using CSOM in PowerShell

powershellsharepointsharepoint-2013

I am aware that using CSOM in PowerShell we can connect to SharePoint Online from local machine, how can we connect to SharePoint 2013 on-premise using CSOM in PowerShell?

Note: I am using System.Net.NetworkCredential to get username and password for On-Premsie

Used the below script, getting the errors while executing it.

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"

function OnPremises-Test {
    $siteUrl = "https://<>/"

    $clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
    $clientContext.Credentials = New-Object System.Net.NetworkCredential("myusername", "password")

    $web = $clientContext.Web 
    $clientContext.Load($web) 
    $clientContext.ExecuteQuery()

Write-Host " Current web title is '$($web.Title)', $($web.Url)"

}

 OnPremises-Test

Below are the errors:

Exception calling "ExecuteQuery" with "0" argument(s): "The remote server returned an error: (403) Forbidden."
At C:\Users\v-krirao\Desktop\test.ps1:17 char:2
+ $clientContext.ExecuteQuery()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException

Best Answer

Although your code works for me on my 2013 site ...Extensions\16\ISAPI... is not specific for SP2013 try the following;

Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
Related Topic