【问题标题】:copy every nth file and retain directory structure复制每个第 n 个文件并保留目录结构
【发布时间】:2018-03-07 16:32:22
【问题描述】:

我需要将文件夹(包括子文件夹)中的每个第 n 个文件复制到另一个位置,但要保持文件夹结构。

我找到了一些 sn-ps,但没有一个完全符合我的要求,它们要么将随机文件复制到一个文件夹,要么复制所有文件但保持文件夹结构。我最接近的是这个。

$Source = "C:\source"
$Destination = "C:\destination"
$Skip = 10

$Files = Get-ChildItem -Recurse -Path $Source -File | ForEach-Object {$_.FullName }

for( $idx = 0; $idx -lt $Files.count; $idx += $Skip ) {
$Files[$idx] | Copy-Item -Destination $Destination -container -recurse
}

当我得到每个第 n 个文件时,我觉得我走在了正确的道路上,但是在目标文件夹中,所有文件都在根目录中并且目录结构丢失了。我认为他可能是由于每 n 个 for 循环不能与 Copy-Item 一起使用并剥离路径?

【问题讨论】:

    标签: powershell


    【解决方案1】:

    将循环更改为:

    for( $idx = 0; $idx -lt $Files.count; $idx += $Skip ) {
        Copy-Item -Path $Files[$idx] -Destination ($Files[$idx]).Replace($Source,$Destination) -Force
    }
    

    这使用完整路径,将$Source 部分替换为$Destination

    -Force 参数表示如果需要,将创建任何父文件夹。

    不确定您的任务是否需要 -Recurse-Container 参数 - 如果需要,请将它们添加回来。

    【讨论】:

    • 尝试了更改,但脚本失败并显示以下内容(我应该补充一点,它确实从根文件夹复制了文件)..... Copy-Item:找不到路径的一部分'C:\copydest\2\files.txt'。在 line:9 char:5 + Copy-Item -Path $Files[$idx] -Destination ($Files[$idx]).Replace( ... + ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~ + CategoryInfo : NotSpecified: (:) [Copy-Item], DirectoryNotFoundException + FullyQualifiedErrorId : System.IO.DirectoryNotFoundException,Microsoft.PowerShell.Commands.CopyItemCommand
    • @Dont-Fight-The-Future 如果不包含 -Force 参数,这就是我所期望的......
    猜你喜欢
    • 2020-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    相关资源
    最近更新 更多