Associate Custom Content Type with SharePoint 2010/2013 List Or Library using PowerShell
To automate deployment in SharePoint 2010/2013 on-premise solution, we have to use PowerShell. One of the deployment activity is creating SharePoint Custom Lists/Libraries and associating them with custom created content types. In this article we will be focusing only how to add/remove content types from the List/Library.
To add content type follow below steps –
- Get Reference to Site collection and root web to get the content types.
[shell]
$siteRef = Get-SPSite http://domain/site
$rootWebRef = $siteRef.RootWeb
[/shell]
- Get the target web reference to which content type will be added for List/Library.
[shell]
$web = Get-SPWeb http://domain/site/web
[/shell]
- Get the reference to target list / library
[shell]
$listRef = $web.Lists[“List Title”]
[/shell]
- Enable the management of content type for this list/library.
[shell]
$listRef.ContentTypesEnabled = $true
$listRef.Update()
[/shell]
- Get the deployed Content Type reference from root web which will be added to the target list.
[shell]
$targetContentType= $rootWebRef.ContentTypes[“CustomContentType”]
[/shell]
- Check if Content is already exists from ContentTypes collection of a List. If not found then add the content type to the list.
[shell]
$contentTypeExist = $listRef.ContentTypes[$contentType.Name]
if($contentTypeExist -ne $null)
{
$listRef.ContentTypes.Add($targetContentType)
$listRef.Update()
}
[/shell]
To delete content type follow below steps –
To delete content type association from list, we have to get the reference of associated content type and pass the Id of content type to Delete method on ContentTypes collection.
[shell]
$contentTypeExist = $listRef.ContentTypes[$contentType.Name]
$listRef.ContentTypes.Delete($contentTypeExist.Id)
[/shell]
This is how the complete code will look like –
[shell]
$siteRef = Get-SPSite http://domain/site
$rootWebRef = $siteRef.RootWeb
$web = Get-SPWeb http://domain/site/web
$listRef = $web.Lists[“List Title”]
if ($listRef -ne $null)
{
$listRef.ContentTypesEnabled = $true
$listRef.Update()
$targetContentType = $rootWebRef.ContentTypes[$contentType.Name]
if($targetContentType -ne $null)
{
$contentTypeExist = $listRef.ContentTypes[$contentType.Name]
if($contentTypeExist -ne $null)
{
Write-Host “Adding Content Type – ” $targetContentType.Name -ForegroundColor Green
$listRef.ContentTypes.Add($targetContentType)
}
else
{
Write-Host ” Content Type already exists – ” $targetContentType.Name -ForegroundColor Green
}
}
$listRef.Update()
}
[/shell]
Happy Coding 🙂