问题
I am trying to copy every 30th file from one folder to another and automate the process for other folders. I have already tried the batch script in this thread: windows batch file script to copy every tenth file from a folder to another folder and just get "The syntax in that command is incorrect" when I run the file (and yes, I've tried both versions).
My folders do have spaces in the names (not my choice and cannot be changed). The files are named image00000X.jpg and yes, there are over 100k of them (which is why I really want the script to work).
Ideally, I'd like a way to set the script up so that I could just change the input and output paths and not have to move the script between the different folders when running it but I'll settle for whatever I can get at this point because I have tried just about everything else (including robocopy, Xcopy, five Powershell scripts, and a few BASH scripts).
Thanks!
回答1:
Here is a simple batch file:
:: copyNth.bat interval sourcePath destinationPath
@echo off
setlocal
set /a n=0
for %%F in ("%~f2.\*") do 2>nul set /a "1/(n=(n+1)%%%1)" || copy "%%F" %3
sampleUsage:
copyNth 30 "c:\someSourcePath" "d:\someDestinationPath"
The "%~f2. is syntax that allows you to safely append a file (or file mask) to any provided path.
The trick to getting every Nth value is to let SET /A intentionally raise a division by 0 error. I redirect the error message to nul and conditionally copy the file only when there was an error.
回答2:
You can also use just a standard for loop. I added some params as well, so you can change the source, destination, and skip count on the fly:
param(
[string]$Source = $( throw "You Must Specify Source Directory" ),
[string]$Destination = $( throw "You Must Specify Destination Directory" ),
[int]$Skip = 30
)
$Files = Get-ChildItem -Path $Source -File
for( $idx = 0; $idx -lt $Files.count; $idx += $Skip ) {
$Files[$idx] | Move-Item -Destination $Destination
}
Source and Destination are required params, but Skip defaults to 30 if you don't specify a value. To use, name it something like move30th.ps1, and run it like:
.\move30th.ps1 -Source "C:\Path\To\Files" -Destination "C:\New\Path" -Skip 30
回答3:
You could do a simple Do/While loop like:
$Files = Get-ChildItem C:\Path\To\Files
$i = 0
Do{
$files[$i]|Move-Item -Dest C:\New\Path
$i=$i+30
}While($i -le $files.count)
来源:https://stackoverflow.com/questions/28183798/batch-file-for-copying-every-nth-file-from-folder1-to-folder2