Tuesday, October 6, 2015

Copy List Items Between SharePoint Lists using PowerShell

Requirement: 
One of our SharePoint list called "News" grown rapidly and wanted to archive its contents to an another list periodically.

Solution: So the task is to copy list items between SharePoint Lists. Lets achieve it using PowerShell.

Important: Both lists should have same columns! So, have the source list saved as template and create a new list from it.
PowerShell Script to copy List Items:
#Configuration variables
$WebURL = "http://intranet.crescent.com"
$SourceListName = "News"
$TargetListName= "NewsArchive"

#Get Objects
$web = Get-SPWeb $WebURL
$SourceList = $web.Lists[$SourceListName]
$TargetList = $web.Lists[$TargetListName]

#Get all source items
$SourceColumns = $sourceList.Fields
$SourceItems = $SourceList.GetItems();

#Iterate through each item and add to target list
Foreach($SourceItem in $SourceItems)
{
    $TargetItem = $TargetList.AddItem()
    Foreach($column in $SourceColumns) 
    {
        if($column.ReadOnlyField -eq $False -and $column.InternalName -ne "Attachments")
        {
             $TargetItem[$($column.InternalName)] = $sourceItem[$($column.InternalName)];
        }
    }
   $TargetItem.Update();
}

Copy Attachments:
If you want to copy attachments, insert this code in Line#26:
#Copy Attachments
Foreach($Attachment in $SourceItem.Attachments)
{
    $spFile = $SourceList.ParentWeb.GetFile($SourceItem.Attachments.UrlPrefix + $Attachment)
    $TargetItem.Attachments.Add($Attachment, $spFile.OpenBinary())
}



You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Check out these SharePoint products:

No comments :

Post a Comment

Please Login and comment to get your questions answered!

You might also like:

Related Posts Plugin for WordPress, Blogger...