Windows – Copy first 10 files from a folder and subfolders

windowsxcopy

I'm trying to get the first (any) 10 files from a deeply nested filestructure. I can use XCOPY source dest /T /E to build the folder structure, but what I'd like to do is get 10 files from each folder and sub folder and copy those as well.

Is there a tool that will do this for me?

Best Answer

Your question sounds like you want the first 10 files from every subfolder? This ought to do it (not exhaustively tested!):

echo off
xcopy /Y %1 %2 /T /E

dir %1 /b /s /A:D >tempfolderlist.txt

for /f "tokens=1 delims=¬" %%a in (./tempfolderlist.txt) do (

    dir "%%a" /b /A:-D >tempfilelist.txt

    setlocal enabledelayedexpansion

    set counter=0

    for /f "tokens=1 delims=¬" %%b in (./tempfilelist.txt) do (

        IF !counter! LSS 10 call :docopy %1 "%%a\%%b" %2
        set /a counter+=1

    )

    endlocal
)

del /q tempfolderlist.txt
del /q tempfilelist.txt
GOTO:EOF

:docopy
set sourcePath=%~1
set sourceFile=%~2
set targetPath=%~3
set sourceNoDrive=%sourceFile:~3,5000%
set sourcePathNoDrive=%sourcePath:~3,5000%
set sourceNoDrive=!sourceNoDrive:%sourcePathNoDrive%\=!

copy "%sourceFile%" "%targetPath%\%sourceNoDrive%" >> out.txt

GOTO:EOF

If it's saved to a batch file named 'first10.cmd', you can use it like this:

first10.cmd "C:\Temp\SourcePath" "C:\Temp\DestPath"

First it prepares the destintation folder structure using xcopy, just as in your question. Then we save a list of all folders to a file, and loop over each one. For each folder, we save a list of all files in that folder, and loop over each file. For each file, :docopy builds the copy command and executes it.