Karine Bosch’s Blog

On SharePoint

Adding Enterprise Keywords to your lists with CSOM


You can find a lot of posts that show you how to add the Enterprise Keyword to your lists and libraries:

$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
$ctx.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
 
$sprootweb = $ctx.Site.RootWeb
$taxKeywordField = $ctx.Site.RootWeb.Fields.GetByInternalNameOrTitle("TaxKeyword");
$list = $sprootweb.Lists.GetListByTitle("Documents");
$ctx.Load($sprootweb)
$ctx.Load($taxKeywordField)
$ctx.Load($list)
$ctx.ExecuteQuery()

$list.Fields.Add($taxKeywordField)
$ctx.ExecuteQuery()

This code snippet works fine if you have no or only one content type on your list or library. But if you have more content types attached to the list or library, only one content type is correctly modified, and it’s not always the default content type. You have to add the Enterprise Keyword column to the other content types yourself:

# get the Enterprise keyword from the list
 $field = $list.Fields.GetById($taxKeywordField.Id)
 $ctx.Load($field)
 $ctx.ExecuteQuery()

# add the Enterprise Keyword to all content types
 $cts = $list.ContentTypes
 $ctx.Load($cts)
 $ctx.ExecuteQuery()
 foreach ($ct in $cts)
 {
    # get all fields associated with the content type
    $fieldRefCollection = $ct.FieldLinks 
    $ctx.Load($fieldRefCollection)
    $ctx.ExecuteQuery()
 
    # add a FieldLink for the Enterprise Keyword
    $fieldLink = New-Object Microsoft.SharePoint.Client.FieldLinkCreationInformation 
    $fieldLink.Field = $field
    $ct.FieldLinks.Add($fieldLink)
    $ct.Update($false)
    $ctx.ExecuteQuery()
 }

And it’s the same story with the views: the Enterprise Keyword is not automatically added to the list views.

 # add the enterprise keyword field to all views
 $views = $list.Views
 $ctx.Load($views)
 $ctx.ExecuteQuery()

 foreach ($view in $views)
 {
    $view.ViewFields.Add($field)
    $view.Update()
 }
 $ctx.ExecuteQuery()
Advertisements

May 1, 2017 - Posted by | CSOM, SharePoint 2013, SharePoint Online

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: