Friday, February 20, 2015

Create a List from Custom Template using Powershell in Sharepoint

Lets consider a situation where we have lots of team sites under a Site collection. Now a new requirement has come and we want to store Team Updates in their corresponding sites.

To do this, creating the custom list with required fields in every list is a long time process. If we create a list in one site and save it as template, we can create New list using this template in other sites. Still manually opening all sites and creating a new list will take long time.

This creation part can be achieved using Powershell. For this, lets assume we created a list and saved it as template. This template will be available in site collection. We can also import List template to Site Collection gallery from external.

Now, open the server and use below Powershell commands in Sharepoint Management Studio

 //Get Site collection through SPSite command  
 $spSite = get-spsite("http://Site Collection URL")  

 //Get current website into which new template to be added  
 $SPWeb = Get-SPWeb("http://Site URL") 
 
 //Get list of all custom templates existing in the site collection  
 $listTemplates = $spsite.GetCustomListTemplates($spweb)  

 //Create list using the above templates, by selecting the custom template you are looking for  
 $SPWeb.Lists.Add("Title of List","Description",$listTemplates["Template Name"])
  

Above example is shown for a single site. We can loop the command for list of sites by storing them into an array or if for all subsites, we can fetch them through command and loop.

As our List template is custom one, we need to follow above steps. If we want to create list from sharepoint's default templates, we can use below commands

 //Get current website into which new template to be added  
 $SPWeb = Get-SPSite("http://SiteURL")  

 //Get list of all templates. Its just for your reference to see list  
 $SPWeb.ListTemplates | Select Name, type, type_client, Description  

 //Create list using the template name. The template name should be in above list  
 $SPWeb.Lists.Add("Title","Description","Template Name")  


You can also save an existing list as a template using below commands

 //Get current website in which the list is created  
 $SPWeb = Get-SPSite("http://SiteURL")  

 //Get the list by using list name which to be saved as template  
 $list = $web.Lists["List Name"]  

 //Use below command to save it as template.   
 //Lat parameter ( 1 / 0 ) indicates if to be stored with data or without data  
 $list.SaveAsTemplate(“Template Name”,”Template Title”,”Template Description”,1)  


No comments:

Post a Comment