PowerShell and connecting to SharePoint Online with CSOM


In my post yesterday I talked about how to connect to SharePoint online using PowerShell. As I stated there are currently 30 different cmdlets available to you that allows you to connect and do stuff with your SharePoint Online. However this list is quite limiting and the only way to do real SharePoint PowerShell is using the SharePoint CSOM.

To be able to connect using CSOM you need to register the Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll, these can be found at the SharePoint root\ISAPI\ folder of a SharePoint OnPrem or you can download the SharePoint Server 2013 Client Components SDK.

In this example today I’m going to show how to get all the properties for a given Web.

$userName = "myUser@SharePoint.com"
$password = "passwordAsString"
$siteCollectionUrl = "https://myonlinesite.sharepoint.com/site/cannonfodder"
#Secure the password
$securePassword = ConvertTo-SecureString $password –AsPlainText –false
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"
#Create a Context
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteCollectionUrl)
#Authorise
$ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userName, $securePassword)
$web = $ctx.Web
$properties = $web.AllProperties
$ctx.Load($web)
$ctx.Load($properties)
$ctx.ExecuteQuery()
Write-Host " Current web title is '' $($web.Title)'', $($web.Url)"
Write-Host "Properties are "
foreach($prop in $properties)
{
 $prop.FieldValues
}

Alternativatively instead of going through this hassle for getting the web properties, you could get them using the REST API.

https://myonlinesite.sharepoint.com/sites/cannonfodder/_api/web/allProperties

Advertisements