下面的代码假设有文件夹folder_a 和folder_b。您的图像在folder_a 中,代码会将这些图像移动到folder_b\folder_1\...、folder_b\folder_2\...、folder_b\folder_3\... 等。根据您的实际需要更改这些目录名称。在folder_a 中运行它,它将完成工作。
$split_at = 5000
# First, create the directories to store the images
$image_count = Get-ChildItem -File | Measure-Object | Select-Object -ExpandProperty Count
1..[math]::Ceiling($image_count/$split_at) | %{New-Item -Name "folder_$($_)" -ItemType Directory -Path "..\folder_b"}
# Then move the images in batch to the destination directories
$folder_n = 1
while(Test-Path .\*) {
Get-ChildItem | select -First $split_at | Move-Item -Destination "..\folder_b\folder_$($folder_n)" -Force
$folder_n++
}
基准测试
我对我的代码和 Manuel Batsching 的代码进行了基准测试。事实证明我的代码更快。下面是基准测试代码和结果。在这里,我每轮创建 2999 个图像文件,并将它们从 folder_a 移动到 folder_b(在文件系统中处于同一级别)。
Remove-Item -Path ..\folder_b\* -Force -Recurse
1..2999 | %{New-Item -Name "item $_.jpg"}
Measure-Command {
$split_at = 43
# First, create the directories to store the images
$image_count = Get-ChildItem -File | Measure-Object | Select-Object -ExpandProperty Count
1..[math]::Ceiling($image_count/$split_at) | %{New-Item -Name "folder_$($_)" -ItemType Directory -Path "..\folder_b"}
# Then move the images in batch to the destination directories
$folder_n = 1
while(Test-Path .\*) {
Get-ChildItem | select -First $split_at | Move-Item -Destination "..\folder_b\folder_$($folder_n)" -Force
$folder_n++
}
}
Remove-Item -Path ..\folder_b\* -Force -Recurse
1..2999 | %{New-Item -Name "item $_.jpg"}
Measure-Command {
$i = 1
while (($files = Get-ChildItem *.jpg, *.jpeg).Count -gt 0)
{
$folderPath = "..\folder_b\folder_$($i)"
New-Item -Type Directory $folderPath
$files | Select-Object -First 43 | Move-Item -Destination $folderPath
$i += 1
}
}
结果(我的代码):
Days : 0
Hours : 0
Minutes : 0
Seconds : 7
Milliseconds : 632
Ticks : 76323557
TotalDays : 8.83374502314815E-05
TotalHours : 0.00212009880555556
TotalMinutes : 0.127205928333333
TotalSeconds : 7.6323557
TotalMilliseconds : 7632.3557
结果(Manuel Batsching):
Days : 0
Hours : 0
Minutes : 0
Seconds : 13
Milliseconds : 961
Ticks : 139616227
TotalDays : 0.000161592855324074
TotalHours : 0.00387822852777778
TotalMinutes : 0.232693711666667
TotalSeconds : 13.9616227
TotalMilliseconds : 13961.6227