Using CSOM and PowerShell against an Office 365 / SharePoint Online site

Here you can see how to consume, via CSOM, a SharePoint site hosted on SharePoint Online/Office 365 using PowerShell. First of all you need to load the CSOM libraries in the PowerShell context.

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”

Then you need to reference the site URL, as well as to retrieve the credentials for accessing the site.

$siteUrl = “”
$username = Read-Host -Prompt “Enter username”
$password = Read-Host -Prompt “Enter password” -AsSecureString

Now you are ready to use CSOM to interact with the site. In the following code excerpt I will change the title of the current web site.

$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $password)
$ctx.Credentials = $credentials

$web = $ctx.Web

Write-Host $web.Title
$web.Title += ” – changed remotely”


Notice the usage of the SharePointOnlineCredentials type, as well as the SecureString for storing the password. All the other lines of code are just classic CSOM, simply used inside PowerShell.

That’s all! Enjoy!