Friday 6 January 2012

Adding a Custom Content Type to a document library with Powershell in Sharepoint 2010

Sometimes you will want to add your own Content Types (custom content types) to your list or document libraries (a list basically…). You can do it with the web interface, it is pretty easy, but what about if you need to perform this for 30,000 sites… you don’t want to spend the rest of the year clicking everywhere.

I have created a function , AddContentTypeToDocumentLibraryRemovingOtherContentType, which allows you to Add a Content Type (“DMSDocument”) and remove the default one (“Documents”). Be aware I will remove “Documents” from my list and add the content type from the site. Whart I am doing here is replacing the default “Document” content type with sophisticated Document content type I developed before called “DMSDocument”

You only need to pass:

  1. Name of the site URL
  2. Name of the Document Library
  3. Name of the Content Type to be added
  4. Name of the Content Type you want to remove from your Document Library.
 $_CurrentURL =  "http://sp_server"
 $_DocumentLibraryName = "Document Centre"
 $_ContentTypeToBeRemoved = "Document"
 $_ContentTypeToBeAdded = "DMSDocument"
 
 Function AddContentTypeToDocumentLibraryRemovingOtherContentType($_sCurrentURL,$_sDocumentLibraryName,$_sContentTypeToBeRemoved, $_sContentTypeToBeAdded)
 { 
 		## Getting the website...
  		$SPWeb = Get-SPWeb -Identity $_sCurrentURL		
		
		## Getting the Document Library (list) and enable Content Types
		$List = $SPWeb.Lists[$_sDocumentLibraryName]
		$List.ContentTypesEnabled = $true
		$List.update()
		
		## Getting the content types to be removed
		## NOTE: This particular one, "Document" lives in our list,
		##       so we remove it from there
		$DocumentCT = $List.ContentTypes[$_sContentTypeToBeRemoved]		
		## This Content type lives in the site, so we get it from there
    	         $CustomCT = $SPWeb.ContentTypes[$_sContentTypeToBeAdded]
    	         $List.ContentTypes.Delete($DocumentCT.Id)
		$List.ContentTypes.Add($CustomCT) 		
		$List.update()	
		
		## Disposing SPWEB object to avoid memory leaks.
		$SPWeb.Dispose()
}
AddContentTypeToDocumentLibraryRemovingOtherContentType $_CurrentURL $_DocumentLibraryName $_ContentTypeToBeRemoved $_ContentTypeToBeAdded

Conclusion: Powershell will bring you a high rate of productivity, but don’t forget to dispose the objects, otherwise you could cause memory leaks in your farm.