How to Add Dynamic Timestamps to 7-Zip Backups

Automating 7-Zip backups requires dynamic timestamps in file names to prevent automated jobs from overwriting previous archives and to maintain a clean version history. This guide covers how to dynamically generate date and time strings and pass them into 7-Zip commands using Windows Batch, PowerShell, and Linux Bash scripts.

Windows Batch Script Method

Standard Windows command scripts (.bat or .cmd) can extract the current date and time using environment variables or a locale-independent Windows command.

Because standard %DATE% formatting changes based on regional settings, using PowerShell within the batch file ensures a consistent YYYY-MM-DD_HHMMSS format regardless of system language:

@echo off
:: Generate a locale-independent timestamp
for /f "tokens=*" %%i in ('powershell -NoProfile -Command "Get-Date -Format 'yyyy-MM-dd_HHmmss'"') do set TIMESTAMP=%%i

:: Define paths
set "SEVENZIP=C:\Program Files\7-Zip\7z.exe"
set "SOURCE=C:\DataToBackup"
set "DEST=D:\Backups\Backup_%TIMESTAMP%.7z"

:: Run 7-Zip
"%SEVENZIP%" a -t7z "%DEST%" "%SOURCE%" -mx=9

Native String Parsing Method

If your environment restricts executing PowerShell, extract substrings from %DATE% and %TIME%. Ensure the indices match your local date format:

@echo off
:: Assumes MM/DD/YYYY format; adjust substring offsets if using DD/MM/YYYY
set YYYY=%date:~6,4%
set MM=%date:~0,2%
set DD=%date:~3,2%

:: Handle single-digit hours replacing space with leading zero
set HH=%time:~0,2%
if "%HH:~0,1%" == " " set HH=0%HH:~1,1%
set MIN=%time:~3,2%
set SS=%time:~6,2%

set "TIMESTAMP=%YYYY%-%MM%-%DD%_%HH%%MIN%%SS%"
"C:\Program Files\7-Zip\7z.exe" a "D:\Backups\Backup_%TIMESTAMP%.7z" "C:\DataToBackup"

Windows PowerShell Method

PowerShell provides native date formatting and avoids string-parsing errors across different regional configurations.

# Define the timestamp format (Year-Month-Day_Hour-Minute-Second)
$Timestamp = Get-Date -Format "yyyy-MM-dd_HHmmss"

# Define backup paths
$SevenZip = "C:\Program Files\7-Zip\7z.exe"
$SourcePath = "C:\DataToBackup"
$Destination = "D:\Backups\Backup_$Timestamp.7z"

# Execute 7-Zip
& $SevenZip a -t7z $Destination $SourcePath -mx=7

Linux / Bash Method

For Linux environments utilizing p7zip, extract the timestamp directly using the date utility:

#!/bin/bash

# Generate timestamp
TIMESTAMP=$(date +"%Y-%m-%d_%H%M%S")

# Define paths
SOURCE="/var/data"
DESTINATION="/mnt/backups/backup_${TIMESTAMP}.7z"

# Run 7-Zip
7z a -t7z "$DESTINATION" "$SOURCE"

Common 7-Zip Flags for Backup Scripts

  • a: Adds files to the archive.
  • -t7z: Sets the archive format to .7z (can be replaced with -tzip).
  • -mx=[1-9]: Defines the compression level (1 for fastest, 9 for ultra compression).
  • -r: Recursively traverses subdirectories.
  • -p[password]: Encrypts the archive with a password.
  • -mhe=on: Encrypts archive headers so file names are hidden when using 7z format.