In SP2010, I'm trying to move all the files from one library to another using Powershell.
I'm using the below script to first copy the files from source to destination and then delete the source file.
But the script displays error after the first file is moved to destination and then deleted from source.I understand the script is not able to get back to the foreach loop after processing the first file , i tried different ways but nothing worked.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
#Custom Function to Copy Files from Source Folder to Target
Function Copy-Files($SourceFolder, $TargetFolder)
{
write-host "Copying Files from:$($SourceFolder.URL) to $($TargetFolder.URL)"
#Get Each File from the Source
$SourceFilesColl = $SourceFolder.Files
#Iterate through each item from the source
Foreach($SourceFile in $SourceFilesColl)
{
#Copy File from the Source
$NewFile = $TargetFolder.Files.Add($SourceFile.Name, $SourceFile.OpenBinary(),$True)
#Copy Meta-Data from Source
Foreach($Field in $SourceFile.Item.Fields)
{
If(!$Field.ReadOnlyField)
{
if($NewFile.Item.Fields.ContainsField($Field.InternalName))
{
$NewFile.Item[$Field.InternalName] = $SourceFile.Item[$Field.InternalName]
}
}
}
#Update
$NewFile.Item.UpdateOverwriteVersion()
Write-host "Copied File:"$SourceFile.Name
$SourceFile.Delete()
Write-host "Deleted File from source:"$SourceFile.Name
}
}
#Variables for Processing
$WebURL="http://SiteURL"
$SourceLibrary ="Team Docs"
$TargetLibrary = "Sales Documents"
#Get Objects
$Web = Get-SPWeb $WebURL
$SourceFolder = $Web.GetFolder($SourceLibrary)
$TargetFolder = $Web.GetFolder($TargetLibrary)
#Call the Function to Copy All Files
Copy-Files $SourceFolder $TargetFolder
SP2010 Powershell Error: