Mambo4
Mambo4

Reputation: 192

Copy by file type, from sub-directories, to a single folder?

I have a ton of PNGs in nested subfolders. I want to copy them all to a single destination folder. I have many sets of these to do.

Using robocopy [sourcefolder] [destfolder] *.png /s copies the subfolders as well, which I do not want.

Upvotes: 2

Views: 4891

Answers (2)

Peter Horsley
Peter Horsley

Reputation: 1756

1r0n1k's answer is good, but not quite correct since it includes /s (recurse source directory). Recusing source directory prevents this script from achieving it's purpose as stated by OP. Here's my tweaked version (for three levels of nesting) that also reduces console output to a minimum:

@echo off

set sourcefolder=c:\code\tools-repo
set destfolder=c:\tools
set filespec=*.exe

for /f %%d in ('dir %sourcefolder% /b /ad') do (
    robocopy %sourcefolder%\%%d %destfolder% %filespec% /njh /njs /xx

    for /f %%e in ('dir %sourcefolder%\%%d /b /ad') do (
        robocopy %sourcefolder%\%%d\%%e %destfolder% %filespec% /njh /njs /xx
        
        for /f %%f in ('dir %sourcefolder%\%%d\%%e /b /ad') do (
            robocopy %sourcefolder%\%%d\%%e\%%f %destfolder% %filespec% /njh /njs /xx
        )        
    )
)

I found this useful to copy all exe files from within a large solution to a single folder.

Upvotes: 0

1r0n1k
1r0n1k

Reputation: 395

You can accomplish this with a for-loop:

for /f %%d in ('dir %sourcefolder% /b /ad') do (
    robocopy %sourcefolder%\%%d %destfolder% *.png /s
)

Note that this will only work with one level of subfolders, if you have more, you'd have to use nested for-loops. That would look like this:

for /f %%d in ('dir %sourcefolder% /b /ad') do (
    robocopy %sourcefolder%\%%d %destfolder% *.png /s

    for /f %%e in ('dir %sourcefolder%\%%d /b /ad') do (
        robocopy %sourcefolder%\%%d\%%e %destfolder% *.png /s
    )
)

Just remember that each for-loop has to have its own variable (e.g. %%d or %%e). If you have many levels of subfolder this might get a bit hairy, then I'd consider switching to another scripting language.

Upvotes: 1

Related Questions