Sunday 9 October 2011

How to copy a list using powershell script in Sharepoint 2007 and Sharepoint 2010

Hi,

I recently published an article on copying sharepoint lists programmatically. Someone asked to provide powershell scripts to carry out the same. Hence I created this script. This works with Sharepoint 2007 and Sharepoint 2010 as well.


param([switch]$help)

[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

function GetHelp() {


$HelpText = @"

DESCRIPTION:
This script copies a list within the same site collection as per the parameters.

"@
$HelpText

}

function RahulCopyListSameSiteCollection() {

write-host "This script copies a list within the same site collection"
        write-host "Please enter the URL of the Source Site"
        $sourceSite = read-host
        write-host "Please enter the name of the source list"
        $sourceListName = read-host
        write-host "Please enter the URL of the Destination Site"
        $destinationSite = read-host
        write-host "Please enter the name of the Destination list"
        $destinationListName = read-host
        write-host "Please enter the description of the Destination list"
        $destinationListDescription = read-host
        $site = New-Object Microsoft.SharePoint.SPSite($sourceSite)
        $web =  $site.OpenWeb()
        $sourceList = $web.Lists[$sourceListName]
        $templateName = $sourceList.Title
        $templateFileName = $sourceList.Title
        $sourceList.SaveAsTemplate($templateFileName, $templateName, $sourceList.Description, $true)
        $listTemplate = $site.GetCustomListTemplates($web)[$templateName]
        $destinationWeb = $destinationSite.Remove(0, $site.Url.Length + 1)
        $destWeb = $site.OpenWeb($destinationWeb)
        $destWeb.Lists.Add($destinationListName, $destinationListDescription, $listTemplate)
        $destWeb.Update()
        $listTemplates = $site.RootWeb.Lists["List Template Gallery"]
        $listTemplateItems = $listTemplates.Items
        foreach($listTemplateItem in $listTemplateItems)
        {
          if($listTemplate.Name.Equals($listTemplateItem["Title"]))
                          {
                              $listTemplateItem.Delete()
                              break
                          }

        }
        write-host "the List is copied"
        $web.Dispose()
        $destWeb.Dispose()
        $site.Dispose()
       
        }

if($help) { GetHelp; Continue }
else
 { RahulCopyListSameSiteCollection }

I hope this will help you out.

Thanks,
Rahul Rashu

No comments:

Post a Comment