Windows – Batch file to ZIP only files in directory or sub directory

batch filecommand linewindowszip

I wanted to know if possible how to create a command line to do the following – if a directory exist ZIP only the contents into a ZIP file. If a directory has sub-directories ZIP only the contents into another ZIP file.

Example:

C:\Directory\sample.txt ZIP only sample.txt
C:\Directory\Directory1\sample1.txt ZIP only sample1.txt
C:\Directory\Directory1\Directory2\sample2.txt ZIP only sample2.txt

So it would have created 3 zip files in C:\Directory and sub-directories.

I will not know the name of the sub-directories so can I also assign some sort of variable that says if there are directories or sub-directories in C:\Directory then start above ZIP(s)?

Thank you,

Paul

Best Answer

Put this in batch file:

REM Usage: ZipFilesRecursively.bat "C:\My Files"
for /R "%~f1" %%F in (*) do 7z a "%%~dpFfiles.zip" "%%F"

It compresses all and only all files to files.zip archive created in C:\My Files directory and all its subdirectories.

Related Question