Home > Mobile >  Do not overwrite existing files on copy
Do not overwrite existing files on copy

Time:11-29

I would like to copy files from folder A which has subfolders to another folder. So that I can see all the files which are in folder A and the subfolders as well.

I used this commands and it works perfectly fine:

md "d:\destination"
cd /d "d:\source\A"
for /r %d in (*) do copy "%d" "d:\destination\"

However, there are some duplicate files. So I get asked to delete the existing file or to delete the duplicate file. Selection I would like to keep both files. Is this possible? And if yes, how can I do this?

CodePudding user response:

  1. Open PowerShell ISE
  2. Paste the scripts listed below into script pane and press play.

Identify all files recursively within a folder

$Source = "C:\Source"
(Get-ChildItem -Path $Source -File -Recurse -Force).FullName
# If you just want the name (Get-ChildItem -Path $Source -File -Recurse -Force).Name

Copy files recursively to from source folder to destination folder

$Source = "C:\Source"
$Destination = "C:\Destination"

# If you need to create the destination folder you can enter; New-Item -ItemType "File" -Path $Destination -Force
Get-ChildItem -Path $Source -File -Recurse -Force | Copy-Item -Destination $Destination -Verbose # -Force
(Get-ChildItem -Path $Destination -File -Recurse -Force).FullName

Edit: I removed the -Force from Copy-Item

Update

I reviewed your question one more time and found that I didn't answer all of your questions. The following script will identify the source/destination directories, identify the file contents of both, verify the directories exist, and copy files from source to destination. It will also copy the duplicate files with a new name with the format "duplicate_name_date_time_extension". You will need to specify the source and destination directories manually.

$Source = "C:\Source"
$Destination = "C:\Destination"

$Source_Content = Get-ChildItem -Path $Source -File -Recurse -Force
$Destination_Content = Get-ChildItem -Path $Destination -File -Recurse -Force

If ((Test-Path $Source) -and (Test-Path $Destination)){
    Foreach ($File in $Source_Content){
        $Date = Get-Date -UFormat "%d %b %Y"
        $Time = Get-Date -UFormat "%H%M%S"
        
        If ($Destination_Content.Name -contains $File.Name){        
            Write-Output "DUPLICATE: 
            Source: $($File.FullName)
            Destination: $Destination\DUPLICATE_$($File.BaseName)_$($Date)_$($Time)_$($File.Extension)"
            Copy-Item $($File.FullName) -Destination "$Destination\DUPLICATE_$($File.BaseName)_$($Date)_$($Time)_$($File.Extension)"
        }
        Else{
            Copy-Item $($File.FullName) -Destination $Destination -Verbose
        }
    }
}
Else{
    New-Item -ItemType "Directory" -Path $Destination -Force -Verbose
}

Start-Transcript
Get-ChildItem -Path $Destination -File -Recurse -Force
Stop-Transcript
  • Related