ken
ken

Reputation: 21

Powershell to 7z a folder with encryption

I am starting out with Powershell, and it seems fun so far. Tonight, I am working on a script that compresses a folder with 7z and adds encryption to the new .7z file (see below).

if (-not (test-path "$env:ProgramFiles\7-Zip\7z.exe")) {throw "$env:ProgramFiles\7-Zip\7z.exe needed"} 
set-alias sz "$env:ProgramFiles\7-Zip\7z.exe"  

$timestamp = get-date -f yyyyMMdd
$Source = "D:\dbbackup\$timestamp-0300" 
$Target = "D:\backup\$timestamp.7z"

sz a -mx=9 $Target $Source -p1234

Ultimately, I need to create an encrypted 7z file out of a folder that is changing every night with the yyyyMMdd, and then followed by a constant number (in this case, yyyyMMdd-0300). With the above script, I can run it, and a new 7z file will be created. However, the password 1234 will not apply. There is no encryption at all.

If I leave out the $timestamp and only run the 7z with the $source and $target, I can successfully create an encrypted 7z file.

Can anyone tell me what I am doing incorrectly?

Upvotes: 1

Views: 6503

Answers (2)

Bartosz X
Bartosz X

Reputation: 2808

Just because it cost me some time to pass directories with spaces I am presenting similar one which solves that issue, the below is an example of how to encrypt a .bak files and send encrypted archive into a shared location:

if (-not (test-path "$env:ProgramFiles\7-Zip\7z.exe")) {throw "$env:ProgramFiles\7-Zip\7z.exe needed"} 
set-alias sz "$env:ProgramFiles\7-Zip\7z.exe"  

$timestamp = get-date -f yyyy-MM-dd
$Source = "C:\backups ang logs\*.bak"
$Target = "\\192.168.12.345\d\DropBoxFolder\My Daily Backups $timestamp.7z"

sz a -mx=0 -pStrongPassword -mhe=on -m0=lzma2 $Target $Source | Out-Null

m0=lzma2 is the compression algorithm (more here)

-mx=0 for LZMA2 means 64KB dictionary, 32 fastbytes, HC4 matchfinder and BCJ filter I have used it here as most native .bak files would be compressed already

mhe=on enables header encryption (more 7z methods here)

Out-Null Hides the output instead of sending it down the pipeline or displaying it (more here)

Upvotes: 0

Jower
Jower

Reputation: 575

I would try the following

if (-not (test-path "$env:ProgramFiles\7-Zip\7z.exe")) {throw "$env:ProgramFiles\7-Zip\7z.exe needed"} 
$sz = ("$env:ProgramFiles\7-Zip\7z.exe") 

$timestamp = get-date -f yyyyMMdd
$Source = "D:\dbbackup\$timestamp-0300" 
$Target = "D:\backup\$timestamp.7z"

Start-Process $sz -argumentList "a", "-mx=9", "$Target", "$Source", "-p1234" -Wait

Upvotes: 3

Related Questions