Click here to Skip to main content
15,881,139 members
Articles / All Topics
Technical Blog

Using CSOM in PowerShell for Office 365

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
14 Dec 2015CPOL2 min read 7.8K   1  
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 the 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:

PowerShell
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:

PowerShell
$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 a 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.

PowerShell
$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:

PowerShell
$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:

PowerShell
$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:

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

You can create a list using:

PowerShell
$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:

PowerShell
$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:

PowerShell
$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:

PowerShell
$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:

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

Retrieve the existing term store:

PowerShell
$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.

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

Now, you can create a termset within this group:

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

Then, create terms within the group:

PowerShell
$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.

The post Using CSOM in PowerShell for Office 365 appeared first on The SharePoint Guide.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --