批量复制文本文档中的文件

Batch to copy files from text document

我找到了很多与以下内容相关的帖子,但还没有找到解决方案!

我有一个包含文件列表的 filelist.txt 文件:

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

我想使用带有 copy、xcopy 或 robocopy 的批处理文件来读取确切的文件并将它们与文件夹一起复制到指定目录,即。结果:

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

在源目录中可能还有其他文件,但不应复制这些文件,只能复制在filelist.txt 文件中找到的文件。所以复制了一个文件结构,但没有未指定的文件。

提前致谢!

如果您想使用纯 PowerShell 方法,您可以使用以下代码:

$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
}

此代码将从给定文本获取每个文件路径,然后创建文件的文件夹树(除驱动器号外)。然后将文件复制到新位置。