@Suresh ,
Per my test, if we specify the overwrite parameter to $true, the Add method will not create duplicate files in the target library:
public Microsoft.SharePoint.SPFile Add (string urlOfFile, byte[] file, bool overwrite);
In your code, the value is set to true, so it will overwrite the existing file instead of creating duplicates:
$TargetFile = $TargetLibrary.RootFolder.Files.Add($TargetFileName, $bytes, $true)
My simple test:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
$WebURL = "http://sp13:36043"
$SourceListName = "List82"
$TargetLibraryName = "Lib7/5"
#Get the Web List and Library objects
$web = Get-SPWeb $WebURL
$SourceList = $web.Lists[$SourceListName]
$TargetLibrary = $web.Lists[$TargetLibraryName]
#Loop through each list item
foreach ($ListItem in $SourceList.Items)
{
if($ListItem.Attachments.Count -gt 0)
{
#Loop through each attachment in the list item
foreach ($Attachment in $ListItem.Attachments)
{
#Get the attachment
$file = $web.GetFile($ListItem.Attachments.UrlPrefix+$Attachment)
$bytes = $file.OpenBinary()
$TargetFileName = $TargetLibrary.RootFolder.Url+"/"+$Attachment
$TargetFile = $TargetLibrary.RootFolder.Files.Add($TargetFileName, $bytes, $false)
Write-Host "Copied to: $($TargetFilename)"
}
}
}
If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.