Showing posts with label 7-zip. Show all posts
Showing posts with label 7-zip. Show all posts

Monday, January 6, 2014

Compress Old Files with PowerShell

The Story


The following PowerShell script will compress files that are older than the specified amount of time. It is handy for archiving IIS Logs, SQL Backups, etc.
The script uses 7-zip so you obviously have to have it installed (or the exe copied somewhere). It's using maximum compression which is resource intensive, if you don't want that just remove the "-mx9 -m0=lzma2" parameters.


The Script

$path = "C:\inetpub\logs\LogFiles\"
$mask = "*.log"

$days = 7

$files = dir $path -Recurse -Include $mask | where {($_.LastWriteTime -lt (Get-Date).AddDays(-$days).AddHours(-$hours).AddMinutes(-$mins)) -and ($_.psIsContainer -eq $false)}


ForEach ($file in $files) {

    & "C:\Program Files\7-Zip\7z.exe" u -mx9 -t7z -m0=lzma2 ($file.FullName + ".7z") $file.FullName
    if ($LASTEXITCODE -eq 0) {
        Remove-Item $file
    }

}

Resources

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



And that's it :)