![](/img/trans.png)
[英]How to move files from a source directory to a destination directory with name of first part of file name?
[英]Copy first N files from source directory to “serialized” destination directory using powershell
Powershell或批處理腳本都將起作用。 我想將每N個文件從目錄A分發到目錄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}
這也可以,將計算應創建多少個新文件夾。
$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)
}
這樣的事情應該做:
$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++
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.