Friday, January 15, 2016

Clone a SharePoint List or Library via Powershell

This Powershell script automates the process of cloning a List. 

Consider the following situation:

- You want to save a list as a template, with the data in the list included.
- You want to then create a new list somewhere else, using that template, after it's been saved.
- You want to delete the List Template after the new list has been created.

This script does all that. 

Add-PSSnapin Microsoft.SharePoint.Powershell
 
        #Get the source and destination sites (SPWeb objects)            
        $site = New-Object Microsoft.SharePoint.SPSite("http://some.sharepointsite.com/sites/somesitecollection")
        $web =  $site.OpenWeb()
        $destinationSite = New-Object Microsoft.SharePoint.SPSite("http://some.sharepointsite.com/sites/someothersitecollection");
        $destinationWeb = $destinationSite.OpenWeb()
 
        #Define the source and destination list names            
        $SourceListName = "The Name of Your Source List";
        $DestinationListName = "My New Destination List";
 
        #Connect to the source list            
        $sourceList = $web.Lists[$SourceListName];
 
        #Create a unique name to use when saving the list as a template.            
        $id = [Guid]::NewGuid()
        $templateName = [String]::Format("{0}-{1}",$sourceList.Title,$id.ToString());
        $templateFileName = $templateName;
 
        #Save the list as a list template. The fourth parameter of the SaveAsTemplate method takes a boolean value indicating whether to save list data with the list.       
     
        $sourceList.SaveAsTemplate($templateFileName, $templateName, $sourceList.Description, $true)
 
        #Get the list template that was just saved            
        $listTemplate = $site.GetCustomListTemplates($web)[$templateName]
 
        #Create a new list at the destination web using the list template created from the source list         
        $destinationWeb.Lists.Add($destinationListName, $sourceList.Description, $listTemplate);
        $destinationWeb.Update()
 
        #Clean Up            
        #Delete the list the list template for, the List Template Fallery            
        $listTemplates = $site.RootWeb.Lists["List Template Gallery"]
        $lt = $listTemplates.Items | ?{$_.Title -eq $templateName}
        if($lt -ne $null){$lt.Delete();}
 
        #Dispose of the SPWeb and SPSite objects            
        $web.Dispose();
        $site.Dispose();
        $destinationWeb.Dispose();
        $destinationSite.Dispose();​

No comments:

Post a Comment