2
votes

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

2

2 Answers

0
votes

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"
0
votes

SharePoint Patterns and Practices (PnP) contains a library of PowerShell commands (PnP PowerShell) that allows you to perform complex provisioning and artifact management actions towards SharePoint. The commands use CSOM and can work against both SharePoint Online and SharePoint On-Premises.

The advantage is code you have written can be simply replaced with one single commandlet.