Pass Passwords in Automated 7-Zip Scripts

Automating 7-Zip tasks requires passing credentials silently without interactive prompts. This guide explains how to pass password strings directly within automated 7-Zip scripts using the command-line interface, covers syntax requirements for both archiving and extraction, details header encryption, and outlines methods to handle special characters safely.

The Core Command Syntax: The -p Switch

7-Zip accepts passwords through the -p switch. Unlike many standard command-line tools, there must be no space between the -p flag and the password string itself.

Creating an Encrypted Archive

To create an archive with a hardcoded password:

7z a output.7z source_folder -pSecretPassword123

Encrypting File Names (-mhe=on)

By default, 7-Zip encrypts file contents but leaves filenames visible inside a .7z archive. To encrypt both the contents and the file listing, combine -p with the -mhe=on flag:

7z a secure_archive.7z source_folder -pSecretPassword123 -mhe=on

Extracting a Password-Protected Archive

To extract an archive non-interactively, use the x command along with the -y flag (assume "yes" to all prompts) to prevent the script from stalling on overwrite prompts:

7z x protected_archive.7z -o"C:\TargetFolder" -pSecretPassword123 -y

Handling Passwords with Spaces or Special Characters

If the password contains spaces or special characters, you must enclose the entire switch or the password value in quotes to prevent shell parsing errors.

  • Windows Command Prompt / Batch:
    7z a backup.7z "C:\Data" -p"My Complex Pass!123"
  • Linux / Bash:
    7z a backup.7z /home/user/data -p'My Complex Pass!123'
    Note: In Bash, use single quotes around the password string to prevent variable expansion or interpretation of symbols like $ or !.

Scripting Best Practices: Using Variables

Hardcoding plain-text passwords directly in source code is a security risk. Instead, store the password in an environment variable or pass it as an argument during runtime.

Windows Batch Example

@echo off
set "ARCHIVE_PASS=SecureToken2026!"
"C:\Program Files\7-Zip\7z.exe" a -t7z archive.7z "C:\Data" -p%ARCHIVE_PASS% -mhe=on -y

Linux Bash Example

#!/usr/bin/env bash
ARCHIVE_PASS="SecureToken2026!"
7z a -t7z archive.7z /var/log/app -p"${ARCHIVE_PASS}" -mhe=on -y

PowerShell Example

$Password = "SecureToken2026!"
& "C:\Program Files\7-Zip\7z.exe" a -t7z "backup.7z" "C:\Data" "-p$Password" -mhe=on -y