In this article, let us see, how to add Content Types to a List/Library using PowerShell in SharePoint. The script is very simple and straight forward.
$LogTime = Get-Date -Format yyyy-MM-dd_hh-mm
$LogFile = ". 9.AddContentTypesToPagesLibrary-$LogTime.rtf"
cls
##================================================================================================
## Description : Add Content Types to Pages Library in Authoring Site Collection
## Author : Sathish Nadarajan
## Date :
##================================================================================================
$Host.UI.RawUI.WindowTitle = "-- Add Content Types --"
$StartDate = Get-Date
Write-Host -ForegroundColor White "------------------------------------"
Write-Host -ForegroundColor White "| Add Content Types To Pages Library |"
Write-Host -ForegroundColor White "| Started on: $StartDate |"
Write-Host -ForegroundColor White "------------------------------------"
########################################################### Set the Exxecution Path #########################################
$scriptBase = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent
Set-Location $scriptBase
#start-transcript $logfile
$ErrorActionPreference = "Continue"
$siteCollectionURL = "http://mysitecollection.com"
$siteCollection = Get-SPSite $siteCollectionURL
$webRoot = $siteCollection.RootWeb
#$webRoot.ContentTypes
$siteCollection | Get-SPWeb -limit all | ForEach-Object{
$web=Get-SPWeb $_.Url
Write-Host $web.Title
$customContentTypes = "CT1, CT2, CT3"
Write-Host "Content Types are " $customContentTypes
$docLib = $web.Lists["Pages"]
write-host "Pages Document Library Name : " $docLib.Title
$docLib.ContentTypesEnabled = $true
$docLib.update();
$customContentTypeArray = $customContentTypes.Split(",")
write-host $customContentTypeArray
foreach($customContentType in $customContentTypeArray)
{
write-host "adding Content Type " $customContentType
#Write-Host $siteCollection.ContentTypes[$customContentType];
$customCT = $webRoot.ContentTypes[$customContentType]
#write-host $customCT;
$docLib.ContentTypes.Add($customCT)
}
$docLib.update()
}
Happy Coding.
Sathish Nadarajan.
Leave a comment