Search code examples
batch-filecopy

How to create a Batch file to copy zips in subfolders to another folder


I have a folder called Private, which contains a number of subfolders. Each of those folders contain a number of zip files.

Now I would like to create a batch file to copy all the zips in all the subfolders containing the letters Win to another folder. The source path is F:\_QA\Private\ and the destination is F:\_QA\Zips\.

I initially tried just for testing to copy all the zips using

XCOPY F:\_QA\Private\ F:\_QA\Zips\

which didn't seem to work.


Solution

  • You'll want to use the dir command which can output all zip files recursively, and then filter the output and copy the results. Here is a tested script that does just that:

    @echo off
    
    set "fromPath=F:\_QA\Private"
    set "destinationPath=F:\_QA\Zips"
    
    if not exist "%destinationPath%" mkdir "%destinationPath%"
    
    :: The findstr is to filter a case-sensitive "Win", as the dir command
    :: is always case-insensitive. Feel free to remove that part.
    for /f "delims=" %%A in ('dir "%fromPath%\*Win*.zip" /b /s ^| findstr /r /c:"\\[^^\\]*Win[^^\\]*.zip$"') do (
        echo Copying "%%A"...
        copy /y "%%A" "%destinationPath%" > NUL
    )
    
    echo.
    echo Complete!
    pause
    

    First we find all zip files recursively in that folder, then we filter the output with a the following regex expression:

    \\[^^\\]*Win[^^\\]*.zip$

    This filters only zip files with Win in the name.

    See dir and findstr for more details regarding those commands.