1

I have been asked to see if I can copy many files from a source that has directories and sub directories and for the taget to be a single directory. All files to one directory. If there happens to be a duplicate file they would just copy with different file name like ...(1). I have attempted to ROBOCOPY but so far have not found a switch that helps me with the task.

Thank you!

mebermudez
  • 11
  • 1

1 Answers1

2

This can be done easily with powershell.

# Set the source and destination paths (No trailing slash)
$source = "C:\subtree"
$dest = "C:\consolidated"

# Get a list of all files recursively
$files = Get-ChildItem -Path $source -Recurse

# Process each file
$files | ForEach-Object {
    # Basename is filename w/o ext
    $baseName = $_.BaseName
    $ext = $_.Extension
    # Build initial new file path
    $newName = "$dest\$($_.Name)"

    # Check for duplicate file
    If (Test-Path $newName) {
        $i = 0
        # While the file exists, increment the number that will be appended
        While (Test-Path $newName) {
            $i++
            $newName = "$dest\$baseName($i)$ext"
        }
    } 
    # If the file is not a duplicate, write the (placeholder) file.
    Else {
        New-Item -ItemType File -Path $newName -Force
    }

    # Copy the file contents to the destination
    Copy-Item $_.FullName -Destination $newName -Force
}

Since you are new to powershell, I will suggest using the Powershell ISE that comes included. It will allow you to paste this script in and work through it more easily.

Cory Knutson
  • 1,866
  • 12
  • 20