Compressing and backing up files with 7-Zip from the command line
7-Zip command lines to compress files and folders, and a PowerShell backup example that removes old archives.
This page gathers useful 7-Zip command lines to compress files and folders from a command prompt, plus a PowerShell example that creates a backup and then deletes the oldest archives.
Options used
| Option | Effect |
|---|---|
a |
Adds files to an archive (creates it if needed) |
-t7z |
7z archive format |
-m0=LZMA2 |
LZMA2 compression method |
-mx=0 to -mx=9 |
Compression level (0 = store without compression, 9 = maximum) |
-ms=on |
Solid archive (files are compressed together in blocks) |
-mmt=n |
Number of compression threads |
-mhe=on |
Encrypts the archive header (requires -p) |
-p<PASSWORD> |
Archive password |
-r |
Recurse into sub-folders |
-x!pattern |
Exclude files or folders |
References: 7-Zip, add command and 7-Zip, compression methods.
One archive per file
Each file in the current folder is compressed into its own .7z file:
FOR %i IN (*.*) DO "C:\Program Files\7-Zip\7z.exe" a -t7z -m0=LZMA2:d64k:fb32 -ms=8m -mmt=30 -mx=1 "%~ni.7z" "%i"
A variant handles only some file types, recursively:
for /R "C:\Path\To\Folder\" %A in (*.txt *.doc) do "C:\Tools\7-Zip\7z.exe" a -t7z -m9=LZMA2 "%A.7z" "%A"
In this case each archive is placed next to the file it contains, so archives end up in every sub-folder.
One archive per folder
for /D %A in (*) do "C:\Tools\7-Zip\7z.exe" a -t7z -m9=LZMA2 "%A.7z" "%A"
Each sub-folder of the current folder produces one archive.
ZIP archive with 7za
7za a -mm=Deflate -mfb=258 -mpass=15 -r C:\Path\To\Archive.zip C:\Path\To\Files\*
PowerShell backup script
This script compresses several sub-folders of C:\dev, merges the per-folder archives into one archive stored without compression, deletes the intermediate archives, then deletes the .7z files in the backup folder whose creation date is more than 10 days old.
<# declare function #>
Function Write-Log {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$False)]
[ValidateSet("INFO","WARN","ERROR","FATAL","DEBUG")]
[String]
$Level = "INFO",
[Parameter(Mandatory=$True)]
[string]
$Message,
[Parameter(Mandatory=$False)]
[string]
$logfile
)
$Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
$Line = "$Stamp $Level $Message"
If($logfile) {
Add-Content $logfile -Value $Line
}
Else {
# set the new color
$fc = $host.UI.RawUI.ForegroundColor
switch ($Level) {
"INFO" {$host.UI.RawUI.ForegroundColor = "Green" ;break;}
"WARN" {$host.UI.RawUI.ForegroundColor = "Yellow" ;break;}
"ERROR" {$host.UI.RawUI.ForegroundColor = "Red";break;}
"FATAL" {$host.UI.RawUI.ForegroundColor = "Red";break;}
"DEBUG" {"";break;}
}
Write-Output $Line
$host.UI.RawUI.ForegroundColor = $fc
}
}
Clear-Host
<# init #>
$7z = "c:\tools\7-Zip\7z.exe"
$currentDate = (Get-Date).ToString('yyyyMMddHHmm')
$pathdev = "C:\dev\"
$limit = (Get-Date).AddDays(-10)
Write-Log -Level "INFO" -Message "start backup file"
try {
<# main #>
if (-not (test-path $7z)) {throw "7z.exe needed"}
set-alias sz $7z
[Array]$typePrj = 'config','languages','databases','docker' ,'analyse'
<# backup #>
foreach($item in $typePrj){
Write-Log -Level "INFO" -Message ("7z compress" + $item)
[Array]$zipArgs = ("`""+ $pathdev +""+$currentDate+"_"+ $item +"_backup.7z`""), ("`""+ $pathdev +"\"+ $item +"\`"")
sz a -r -mx=9 -t7z -m0=lzma2 -ms=on -mhe=on -x'!*/.git' $zipArgs[0] $zipArgs[1]
}
foreach($item in $typePrj){
Write-Log -Level "INFO" -Message ("7z merge " + $item)
[Array]$zipArgs = ("`""+ $pathdev +""+$currentDate+"_all_backup.7z`""), ("`""+ $pathdev +""+$currentDate+"_"+ $item +"_backup.7z`"")
sz a -t7z -mx=0 -ms=on -mhe=on -p<PASSWORD> $zipArgs[0] $zipArgs[1]
}
foreach($item in $typePrj){
Write-Log -Level "INFO" -Message ("Remove temp file " + $item)
Remove-Item ($pathdev +""+$currentDate+"_"+ $item +"_backup.7z")
}
<# clean #>
Write-Log -Level "INFO" -Message "clean old file "
Get-ChildItem $pathdev | Where-Object { $_.name -like "*.7z" -and !$_.PSIsContainer -and $_.CreationTime -lt $limit } | ForEach-Object($_) {remove-item $_.fullname}
#| Out-File "toDeleteFiles.txt"
# | Out-File "D:\data\toDeleteFiles.txt" #| foreach($_) {remove-item $_.fullname}
}
catch
{
write-host "Backup an exception:" -ForegroundColor Red
write-host "Backup type: $($_.Exception.GetType().FullName)" -ForegroundColor Red
write-host "Backup message: $($_.Exception.Message)" -ForegroundColor Red
write-host "Error: " $_.Exception -ForegroundColor Red
$erroToLog = "Caught an exception:`r`n" `
+"Exception type: $($_.Exception.GetType().FullName)`r`n" `
+"Exception message: $($_.Exception.Message)`r`n" `
+"Error: $($_.Exception)"
Write-Log -Level "ERROR" -Message $erroToLog
}
Write-Log -Level "INFO" -Message "End backup file"
Notes
- The archive password was written in clear text in the original script. It is replaced here by
<PASSWORD>: store it in a secret vault, never in the script. - In a
.batfile the loop variable is written%%i(or%%A) instead of%i(or%A), which are the forms used at the command prompt. - The script is taken from the original note and has not been validated. Test it on a test folder before any real use, because deleted archives cannot be recovered.