首页 > 解决方案 > 尝试将同一文件夹结构中文件夹的子文件夹中的每个第 n 个文件复制到文件夹

问题描述

这只会复制空文件夹。我正在尝试将同一文件夹结构中文件夹的子文件夹中的每个第 n 个文件复制到文件夹

$Files = Get-ChildItem "D:\n.a.d\excel backups\autorecover backups\Excel\New folder (2)"
$i = 0
Do{
    $files[$i]|copy-Item -Dest "D:\n.a.d\excel backups\autorecover backups\Excel\New folder (3)"
    $i=$i+2
}While($i -le $files.count)
}

标签: powershell

解决方案


好吧,这是一种方法!可能有一种更清洁的方法,但是这种方法可以工作,并且可以在目标中正确获取文件夹结构。

# Add our paths to variables
$SourceFolder = 'D:\n.a.d\excel backups\autorecover backups\Excel\New folder (2)'
$Destination = 'D:\n.a.d\excel backups\autorecover backups\Excel\New folder (3)'

# Variable for n, where n is the gap between files you want copied
$n = 2

# Get all subfolders
$AllSubFolders = Get-ChildItem $SourceFolder -Recurse -Directory

# Add our source root folder to the folder list
$AllFolders = $AllSubFolders.FullName + $SourceFolder

# Loop over all folders, figure out the correct destination folder path by joining the destination +
# the current folder with the $SourceFolder part removed (that's the .SubString-part) and create matching
# folders in the destination, then get all files in the folder and copy every nth file in a similar manner
# as your question.
foreach ($Folder in $AllFolders) {
    $CurrentDestFolder = (Join-Path $Destination ($Folder.Substring($SourceFolder.Length)))
    [void](New-Item -Path $CurrentDestFolder -Force -ItemType Directory)
    $CurrentFiles = Get-ChildItem $Folder -File
    $i = 0
    while ($i -lt $CurrentFiles.Count) {
        $CurrentFiles[$i] | Copy-Item -Destination (Join-Path $CurrentDestFolder $_)
        $i = $i+$n
    }
}

推荐阅读