【问题标题】:Batch to copy files from text document批量从文本文档中复制文件
【发布时间】:2015-07-08 17:28:17
【问题描述】:

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

我有一个包含文件列表的 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 文件中的文件。所以创建了一个副本文件结构,但没有未指定的文件。

提前致谢!

【问题讨论】:

  • for /F "delims=" %x in (filelist.txt) do @echo %~dx "%~px" "%~nxx" 可能是一个起点。读取整个 for /?(最多替换FOR变量
  • 您的结果示例是错误的。 “sample2.txt”文件应该是C:\copy_folder\test2\sample2.txt,同样的点适用于其余文件,第一个文件是错误的,应该是C:\copy_folder\sample1.txt。这些不同的结果中的哪一个是您想要的?
  • 抱歉 Aacini,第一个是正确的方法。我已经修改了问题以反映这一点。

标签: powershell batch-file copy xcopy robocopy


【解决方案1】:

如果您想使用纯 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
}

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

【讨论】:

  • 感谢 Chard,实际上我刚刚使用 PowerShell 采用了几乎相同的方法 - 感谢您的输入!
猜你喜欢
  • 2015-01-21
  • 2013-11-05
  • 2014-07-15
  • 1970-01-01
  • 1970-01-01
  • 2021-09-04
  • 1970-01-01
  • 2011-10-17
  • 1970-01-01
相关资源
最近更新 更多