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()
No comments yet.
Leave a Reply