SharePoint 2013 – Getting Content Type by Name – CSOM

Following scenario is using PowerShell and the Client Side Object Model..

Task: Get a specific Content Type by name rather than ID – as we don’t know what the ID is!

### ASSUMES CONNECTION TO CLIENT CONTEXT - $CTX ###
# Get the web context
$web = $ctx.Web
$ctx.Load($web)
$ctx.ExecuteQuery(
# Gets a collection of available content types
$contentTypesColl = $web.AvailableContentTypes
$load = [Microsoft.SharePoint.Client.ClientContext].GetMethod("Load")
$listLoad = $load.MakeGenericMethod([Microsoft.SharePoint.Client.ContentTypeCollection])
$listLoad.Invoke($ctx,@($contentTypesColl,$null))
$ctx.ExecuteQuery()
# Iterate through the content types matching the name
# Once match is found, save content type ID to a variable
$LegalDocId = 0;
foreach($ctype in $contentTypesColl)
{
$i = 0
if($ctype[$i].Name -eq "Legal Document")
{
Write-Host $ctype[$i].Name -ForegroundColor Cyan
$LegalDocId = $ctype[$i].Id
break;
}

$i++
}
# Once content type ID is found, apply content type to a document library
if($LegalDocId -ne '0')
{
# Get the library
$lib = $web.Lists.GetByTitle("Documents")
$ctx.Load($lib)

# Enable content types
$lib.ContentTypesEnabled = $true
$lib.Update()
# Apply the content type
$contentType = $web.ContentTypes.GetById($LegalDocId.ToString())
$ctx.Load($contentType)
Add-LogMessage -message "Adding content type to library"
$ctx.Load($lib.ContentTypes.AddExistingContentType($web.ContentTypes.GetById($LegalDocId.ToString())))

# Update the library
$lib.Update()
$ctx.ExecuteQuery()
}
Advertisements