Search code examples
powershellbatch-filecopyxcopyrobocopy

Batch to copy files from text document


I have found a number of posts relating to the following but have not yet made my way to a solution!

I have a filelist.txt file contaning a list of files:

C:\test1\sample1.txt
C:\test2\sample2.txt
C:\test3\folder1\sample3.txt
C:\test3\folder1\sample4.txt
C:\test3\folder1\folder2\sample5.txt

I want to use a batch file with copy, xcopy or robocopy to read the exact files and copy them to a specified directory along with the folders ie. resulting:

C:\copy_folder\test1\sample1.txt
C:\copy_folder\test2\sample2.txt
C:\copy_folder\test3\folder1\sample3.txt
C:\copy_folder\test3\folder1\sample4.txt
C:\copy_folder\test3\folder1\folder2\sample5.txt

In the source directories a there may be other files, but these should not be coppied, only those found in the filelist.txt file. So a replica filestructure is made but without unspecified files.

Thanks in advance!


Solution

  • If you want to use a pure PowerShell method you could use the following code:

    $destination = "C:\copy_folder"
    $textFileWithPaths = "C:\filelist.txt"
    
    Get-Content $textFileWithPaths | % {
        # Create the destination folder path
        $NewFolder = Split-Path (Join-Path $destination $_) -Parent | Split-Path -NoQualifier`
    
        # Check if the path exsists - create if it doesn't exsist
        If(!(Test-Path $NewFolder)){
            New-Item -ItemType Directory -Path $NewFolder -Force
        }
        # Copy the file to new location
        Copy-Item $_ $NewFolder -Force
    }
    

    This code will take each file path from a given text, and then create the folder tree of the file (all but the drive letter). Then make a copy of the file to the new location.