Question

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?

Was it helpful?

Solution 3

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"

OTHER TIPS

Assuming you are using 7zip for command line, you should be able to use the following script:

@ECHO OFF
for /d %%a in (*) do (7za a -tzip %%~na.zip "%%a")
for /d %%a in (*) do (if exist "%%a\" del "%%a")
pause

To use it, whack the batch file in the 'logtype' folder you mentioned, and run it.

Command sets are the right things to perform such tasks correctly.

command && command_OK || command_Fail

command_OK will be executed only if command finished successfully and command_Fail will be executed in case of error. Typical use of this pattern:

call %archiver% %file% && (del %file%) || (exit /b 1)

But in this very case you won't need any additional commands. Luckily 7zip features wonderful -sdel option which does the trick.

Here is what I use for folders.

@echo off
for /D %%d in (*) do (
7z a t -mx9 -t7z -y "%%~nd.7z" "%%~fd" 
if exist "%%~nd.7z" rmdir /s /q "%%~fd"
else
echo The file "%%~fd" DOES NOT exist
pause
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top