Friday, December 10, 2010

7-zip compress full paths from directory listing

7-zip is an excellent free tool for file compression, but it lacks a feature that is very annoying.

This is preserving the absolute path of the files in an archive. When adding multiple files one-by-one, eg. with a batch script, this can cause lots of headaches. The same happened to me, until I wrapped up this little batch script that will CROP down the trailing drive letters from a directory listing. In this example I will list files that have been changed since a specific date but a dir /s /b > filelist.txt will also do the job (look out for the correct quotation marks that might differ between forfiles and dir)

@echo off
REM -- you need this for dynamic variables
setlocal ENABLEDELAYEDEXPANSION
REM -- date since files have changed
set Since=11/25/2010
REM -- root path for the data being archived as well as for the 7z file in this case
set MyAppPath=C:\Inetpub\wwwroot\PDF
REM -- change active directory to root so 7z will like the listing
cd /d C:\
REM -- generate file list
Forfiles -p %MyAppPath% /s /m *.* /D %Since% /C "cmd /C echo @path>>%MyAppPath%\filelist.txt"
REM -- take all lines from filelist.txt, crop down the trailing drive letter and add a " in front
REM -- then execute 7z with the result; 7z will use store compression in this case.
for /f "tokens=* delims= " %%a in (%MyAppPath%\filelist.txt) do (
set PDFPath=%%a
"c:\program files\7-zip\7z.exe" a -t7z -mx0 %MyAppPath%\archive.7z ^"!PDFPath:~4,-1!
)
del filelist.txt