Search code examples
batch-filecompressionbackupscheduled-tasks7zip

Use 7-Zip to Compress folders within a directory and then delete the source folder used to create the .zip file


I need to run a script to compress all folders within a folder that is 2 levels within a directory structure. I want the script to compress all folders within the log folder and then delete the original folder, thus saving loads on space. To illustrate the folders I wish to compress, see below:

Drive Location-->machinename-->logtype-->folders_i_want_to_compress

Within folder 2 there are folders with dates in the format yyyymmdd and it is these that I wish to compress as zip files.

I cannot work out how to create a script to do this but I did find a similar script here:7-Zip compress files within a folder then delete files

... that looks like this:

REM Usage: ZipFilesRecursively.bat "C:\My Files"
for /R "%~f1" %%F in (*) do (
    7z a -mx9 "%%~dpnxF.7z" "%%F"
    if exist "%%~dpnxF.7z" del "%%F"
)

But this is only for files. I cannot work how to change this so that it works for folders rather than files although I believe the start of it would be to use for with the /D switch rather than the /R.

As the path to the folders is based partly on the machine name, I need to feed this into the script, so I was planning on using a call from another batch file to then run the compression/deletion script.

The call script will look something like this

Call zipdeletetest4 machinename1
Call zipdeletetest4 machinename2    
Call zipdeletetest4 machinename3
Call zipdeletetest4 machinename4

Can anyone help with this?


Solution

  • I eventually went for

    REM compress folders to zips
    for /d %%x in ("C:\Logs\*.*") do start "C:\Program Files (x86)\7-Zip\7z.exe" /b /low /wait "C:\Program Files (x86)\7-Zip\7z.exe" a -tzip "%%x.zip" "%%x\"
    
    REM delete the original folders used to create zips
    for /d %%F in ("C:\Logs\*") do rd /s /q "%%F"