将前N个文件从源目录复制到"序列化"使用powershell的目标目录

时间:2015-07-06 07:25:31

标签: windows powershell batch-file cmd

Powershell或批处理脚本都可以使用。我想将目录A中的每N个文件分发到目录B1,B2,B3等

实施例: C:\ a(有9个.jpg文件) file1.jpg file2.jpg ... file9.jpg

然后c:\ b1,C:\ b2,C:\ b3每个应该有3个文件。它应该创建目录C:\ b *。

到目前为止,我想出了这段代码,工作正常但是将目录A中的所有文件复制到目录B中:

$sourceFolder = "C:\a"
$destinationFolder = "C:\b"
$maxItems = 9
Get-Childitem  $sourceFolder\*.jpg | ForEach-Object {Select-Object -First $maxItems | Robocopy $sourceFolder $destinationFolder /E /MOV}

2 个答案:

答案 0 :(得分:1)

这也有效,将计算应创建多少个新文件夹。

$excludealreadycopieditems = @()
$sourcefolder = "C:\a"
$destinationFolder = "C:\b"
$maxitemsinfolder = 3
#Calculate how many folders should be created:
$folderstocreate = [math]::Ceiling((get-childitem $sourcefolder\*.jpg).count / $maxitemsinfolder)
#For loop for the proces
for ($i = 1; $i -lt $folderstocreate + 1; $i++)
     {
#Create the new folders:
New-Item -ItemType directory $destinationFolder$i
#Copy the items (if moving in stead of copy use Move-Item)
get-childitem $sourcefolder\*.jpg -Exclude $excludealreadycopieditems | sort-object name | select -First $maxitemsinfolder | Copy-Item -Destination $destinationFolder$i ;
#Exclude the already copied items:
$excludealreadycopieditems = $excludealreadycopieditems + (get-childitem $destinationFolder$i\*.jpg | select -ExpandProperty name)
     }

答案 1 :(得分:0)

这样的事情应该做:

$cnt = 0
$i   = 1
Get-ChildItem "$sourceFolder\*.jpg" | % {
  if ($script:cnt -ge $maxItems) {
    $script:i++
    $script:cnt = 0
  }

  $dst = "$destinationFolder$script:i"
  if (-not (Test-Path -LiteralPath $dst)) {
    New-Item $dst -Type Directory | Out-Null
  }
  Copy-Item $_.FullName $dst

  $script:cnt++
}