Move the list items from one list to another list using PowerShell - SharePoint 2010


Using below script one can move items from one list to another(including CreatedBy/ModifiedBy which are configured in a list(source,target,item age).

#***************************************************************************
# Moves list/library items from one location to another location for archiving.
Remove-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
$srcListSiteUrl = http://testsite
$ConfigListName = "ArchivalConfiguration"
$IDFieldName = "OldItemID" 
$date = Get-Date -format y
$ldate = Get-Date
$LogDate = $date -replace " ", "_"
$path = "C:\Jobs\ArchivalLog\"
If(!(test-path $path))
{
    New-Item -ItemType Directory -Force -Path $path
}
$Logfile = "$($path)\$($LogDate).log"
Add-content $Logfile -value "******************************************************************************"
Add-content $Logfile -value "Archival begin Date - $($ldate)"
   try
   {
        $sourceListWeb = Get-SPWeb -identity $srcListSiteUrl
        $ConfigList = $sourceListWeb.Lists.TryGetList($ConfigListName)
        if(!$ConfigList)
        {
            Add-content $Logfile -value "Configuration list is not found!!!"
            return
        }  
        $ConfigItemCollection = $ConfigList.GetItems();
        if(!$ConfigItemCollection -or $ConfigItemCollection.count -le 0)
        {
            Add-content $Logfile -value "Configuration list is empty!!!"
            return
        }       
        #Get the lists to be archived from configuration - End
        foreach($configItem in $ConfigItemCollection)
        {
             if((!$configItem["Source List Name"]) -or (!$configItem["Destination List Name"]) -or (!$configItem["Archival Days"]) )
             {
                Add-content $Logfile -value "Configuration list item has one or more values missing!!!"
                return
             }
            
            $SourceList = $sourceListWeb.Lists.TryGetList($configItem["Source List Name"])
            $DestinationList = $sourceListWeb.Lists.TryGetList($configItem["Destination List Name"])
            $MovedIDs = New-Object System.Collections.ArrayList
            # Caliculate archival date - begin
            $expiryDate = (Get-date).AddDays(-$configItem["Archival Days"])
            Add-content $Logfile -value "Moving items from $($configItem["Source List Name"]) to $($configItem["Destination List Name"]) list based on modified date older than $($expiryDate)"
            # Caliculate archival date - end
         
           #Filtering Items based on the Date as we do not want to archive all items in the list     
            $filterQuery = ''   
         $archivalItemsQuery = new-object Microsoft.SharePoint.SPQuery
         $archivalItemsQuery.Query = $filterQuery
            $sourceSPListItemCollection = $SourceList.GetItems($archivalItemsQuery);

            #$DestinationList.Fields.AddFieldAsXml($node.OuterXml, $true,[Microsoft.SharePoint.SPAddFieldOptions]::AddFieldToDefaultView)
            if( $DestinationList.Fields.ContainsField($IDFieldName) -eq $false)
            {
                 #adding ID field type to the Destination list 
                $spFieldType = [Microsoft.SharePoint.SPFieldType]::Number 
                $DestinationList.Fields.Add($IDFieldName, $spFieldType, $false)
            }
            write-host $sourceSPListItemCollection.count
            $delItemCount = $sourceSPListItemCollection.count
            if($delItemCount -gt 0)
            {
                $itemCout = 0           
                while($itemCout -lt $delItemCount)           
                {
       
                    $srcListItem = $sourceSPListItemCollection[$itemCout]
                    $newSPListItem = $DestinationList.AddItem();
              foreach($spField in $srcListItem.Fields)
                    {
               if ($spField.ReadOnlyField -ne $True -and  $spField.InternalName -ne "Attachments")
               {
                   $newSPListItem[$spField.InternalName] = $srcListItem[$spField.InternalName];
               }
              }
              # Handle Attachments
              foreach($leafName in $srcListItem.Attachments)
              {               
                  $spFile = $SourceList.ParentWeb.GetFile($srcListItem.Attachments.UrlPrefix + $leafName)
                        $newSPListItem.Attachments.Add($leafName, $spFile.OpenBinary());
              }  
                    $newSPListItem[$IDFieldName]  = $srcListItem["ID"]
                    $modifiedBy = $srcListItem["Editor"]
                    $newSPListItem["Editor"] = $modifiedBy
                    $modified = $srcListItem["Modified"]
                    $newSPListItem["Modified"] = $modified
                    $createdBy = $srcListItem["Author"]
                    $newSPListItem["Author"] = $createdBy
                    $created = $srcListItem["Created"]
                    $newSPListItem["Created"] = $created
                    $newSPListItem.Update()
                    $MovedIDs.add($srcListItem["ID"])                
                    $itemCout = $itemCout + 1
                }
                $DestinationList.update()    
                Add-content $Logfile -value "Items copied successfully."      
                $sourceSPListItemCollection = $null
                $sourceSPListItemCollection = $SourceList.GetItems($archivalItemsQuery)
                $delItemCount=  $sourceSPListItemCollection.count 
                $itemCout = 0

                #Delete the copied items
                $ditemCount = 0
                $missingIdCount = 0
                while($itemCout -lt $delItemCount -and $ditemCount  -lt $MovedIDs.Count)           
                {       
                    $srcListItem = $sourceSPListItemCollection[$missingIdCount]
                    if($MovedIDs.Contains($srcListItem.id))
                    {
                        #$SourceList.getitembyid($sitem.id).Delete()
                        #$sitem.delete()
                        $srcListItem.delete()
                        $ditemCount = $ditemCount + 1
                    }
                    else
                    {
                        $missingIdCount = $missingIdCount + 1
                        Add-content $Logfile -value "Item with ID: $($srcListItem.id) is not moved to archival list!!!"
                    }
                    $itemCout = $itemCout + 1
                }
                Add-content $Logfile -value "Items deleted successfully."
                #Delete the copied items - End

                Add-content $Logfile -value "Total items moved $($MovedIDs.Count)"
                $ldate = get-date
                Add-content $Logfile -value "List Archival completion Date - $($ldate)"
                $sourceSPListItemCollection = $null           
                $MovedIDs = $null
            }
            else
            {
                Add-content $Logfile -value "There are no archival items to move."
            }
        }
       
    }
 catch
 {
        if($srcListItem)
        {
            Add-content $Logfile -value "Failed to copy item #$($srcListItem['ID'])."
        }
        Add-content $Logfile -value "Exception Thrown - $($_.exception)"
 }
 finally
 {       
     if($sourceListWeb -ne $null){$sourceListWeb.Dispose()}
     if($dstListWeb -ne $null){$dstListWeb.Dispose()}
        $ldate = get-date
        Add-content $Logfile -value "Archival end Date - $($ldate)"
 }

Comments

Popular posts from this blog

SharePoint 2019 New Features

Email Validation for SharePoint list column