Using CSOM in PowerShell for Office 365

In my previous post, we explored using the PowerShell for Office 365. It was good for administrative tasks such as managing the tenant, users and site collection. As of this writing, there are only 33 commands for SharePoint online.

It doesn’t have commands for example to activate features or managing service applications. In this post, we’ll go over using CSOM in PowerShell for Office 365. This will give you access to entire SharePoint API or the object model so you can manage the individual sites, lists, features, service applications etc.

You will need the SharePoint client dlls on your local machine where you are running these PowerShell commands. You can download and install the Client SDK for SharePoint 2013. This can be separately downloaded and installed and it is also part of the Visual Studio Professional edition as well.

First thing you need to do is load the client side assemblies to your session:

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"

Now, initialize the required variables

 $userName = "<office username 365>"; 
$site = "<office 365 url tenant>"; 
$pwd = Read-Host -Prompt "Please enter your password" -AsSecureString ;

Getting the context is the main part. Notice that we are using the command New-Object. This is command which creates the new object. We’ll use this command to create new objects from the CSOM. This is equivalent to the C# new operator.

 $context = New-Object Microsoft.SharePoint.Client.ClientContext($site);
$cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userName,$pwd);
$context.Credentials = $cred;

Now, you can start using the CSOM. For example, access the lists:

 
$lists = $context.Web.Lists;
$context.Load($lists);
$context.ExecuteQuery();
foreach($list in $lists)
{
	Write-Host $list.Title;
}

Or, if you want to list the items of a particular list, you could do:

$contactsList = $lists.GetByTitle("MyContacts");
$query = [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery(100);
$items = $contactsList.GetItems($query);
$context.Load($contactsList);
$context.Load($items);
$context.ExecuteQuery();
foreach($item in $items)
{
    Write-Host $item["FirstName"]
}

There are some subtle differences from the CSOM used in managed code. For example, you cannot use lambda expressions to limit the fields retrieved or specify the Include such as

#this will throw an error!
$context.Load($lists, "Include(Title)"); 

You can create a list using:

$lci = New-Object Microsoft.SharePoint.Client.ListCreationInformation;
$lci.Title = "Custom List";
$lci.TemplateType = '100';
$customList = $lists.Add($lci);
$customList.Update();
$context.ExecuteQuery();

You can add an existing site column to the list

$availableFields = $web.AvailableFields;
$context.Load($availableFields);
$context.ExecuteQuery();
$companyField = $availableFields | Where {$_.Title -eq "Company"}
$context.Load($companyField);
$context.ExecuteQuery();
$customList = $lists.GetByTitle("Custom List");
$context.Load($customList);
$context.ExecuteQuery();
$customList.Fields.Add($companyField);
$customList.Update();
$context.ExecuteQuery();

And add the column to the default view

$defaultView = $customList.DefaultView;
$defaultView.ViewFields.Add("Company");
$defaultView.Update();
$customList.Update();
$context.ExecuteQuery();

Working with features

Let’s say you want to activate the ‘Search Server Web Parts and Templates’ feature. You could do

$featureGuid = New-Object System.Guid "{9c0834e1-ba47-4d49-812b-7d4fb6fea211}"
$context.Site.Features.Add($featureGuid, $true, [Microsoft.SharePoint.Client.FeatureDefinitionScope]::None);
$context.ExecuteQuery();

To find the id of the feature, you can go to the feature listing page. And in the developer tools select the Activate button. The id of the div element will be the feature guid!

Working with Managed Metadata

Get the managed metadata service using the context

$mms = [Microsoft.SharePoint.Client.Taxonomy.TaxonomySession]::GetTaxonomySession($context);
$context.Load($mms);
$context.ExecuteQuery();

Retrieve the existing term store

$termStores = $mms.TermStores;
$context.Load($termStores);
$context.ExecuteQuery();

$termStore = $termStores[0];
$context.Load($termStore);
$context.ExecuteQuery();

Create a group in the term store. I found this really helpful as I couldn’t find a way to create it from the UI of Office 365.

$group = $termStore.CreateGroup("PowerShell", "{C93600E9-49D0-4079-8DBE-8282A8CE4119}");
$context.Load($group);
$context.ExecuteQuery();

Now, you can create a termset within this group

$termSet = $group.CreateTermSet("SharePoint", "{6768B471-7EA3-4981-81A4-EA4902543365}", 1033);
$context.Load($termSet);
$context.ExecuteQuery();

Then, create terms within the group

$term = $termSet.CreateTerm("CSOM", 1033, "{E16CD934-74DB-4D2A-AB39-D24422DBC1B1}");
$context.Load($term);
$context.ExecuteQuery();

I have uploaded the PowerShell code for this article in github at SharePoint-Online-CSOM.ps1

Get Free Email Updates!

Signup now and receive an email once I publish new content.

I will never give away, trade or sell your email address. You can unsubscribe at any time.