PowerShell function to create a password protected zip file
There are a few different ways to create zip files in powershell, but not many that allow you to create one that is password protected. I found this post that shows how to do it using 7zip, so I thought I would share my modified solution.
Here is the function I wrote that uses 7zip to perform the zip, since 7zip supports using a password to zip the files. This script looks for the 7zip executable (7z.exe) in the default install locations, and if not found it will use the stand-alone 7zip executable (7za.exe) if it is in the same directory as the powershell script.
Update: Updated function to support multiple compression types: 7z, zip, gzip, bzip2, tar, iso, and udf.
function Write-ZipUsing7Zip([string]$FilesToZip, [string]$ZipOutputFilePath, [string]$Password, [ValidateSet('7z','zip','gzip','bzip2','tar','iso','udf')][string]$CompressionType = 'zip', [switch]$HideWindow)
{
# Look for the 7zip executable.
$pathTo32Bit7Zip = "C:\Program Files (x86)\7-Zip\7z.exe"
$pathTo64Bit7Zip = "C:\Program Files\7-Zip\7z.exe"
$THIS_SCRIPTS_DIRECTORY = Split-Path $script:MyInvocation.MyCommand.Path
$pathToStandAloneExe = Join-Path $THIS_SCRIPTS_DIRECTORY "7za.exe"
if (Test-Path $pathTo64Bit7Zip) { $pathTo7ZipExe = $pathTo64Bit7Zip }
elseif (Test-Path $pathTo32Bit7Zip) { $pathTo7ZipExe = $pathTo32Bit7Zip }
elseif (Test-Path $pathToStandAloneExe) { $pathTo7ZipExe = $pathToStandAloneExe }
else { throw "Could not find the 7-zip executable." }
# Delete the destination zip file if it already exists (i.e. overwrite it).
if (Test-Path $ZipOutputFilePath) { Remove-Item $ZipOutputFilePath -Force }
$windowStyle = "Normal"
if ($HideWindow) { $windowStyle = "Hidden" }
# Create the arguments to use to zip up the files.
# Command-line argument syntax can be found at: http://www.dotnetperls.com/7-zip-examples
$arguments = "a -t$CompressionType ""$ZipOutputFilePath"" ""$FilesToZip"" -mx9"
if (!([string]::IsNullOrEmpty($Password))) { $arguments += " -p$Password" }
# Zip up the files.
$p = Start-Process $pathTo7ZipExe -ArgumentList $arguments -Wait -PassThru -WindowStyle $windowStyle
# If the files were not zipped successfully.
if (!(($p.HasExited -eq $true) -and ($p.ExitCode -eq 0)))
{
throw "There was a problem creating the zip file '$ZipFilePath'."
}
}
And here’s some examples of how to call the function:
Write-ZipUsing7Zip -FilesToZip "C:\SomeFolder" -ZipOutputFilePath "C:\SomeFolder.zip" -Password "password123"
Write-ZipUsing7Zip "C:\Folder\*.txt" "C:\FoldersTxtFiles.zip" -HideWindow
I hope you find this useful.
Happy coding!
Comments
knarfalingus
Nice function, but for a little more security I’d look into using the -t7z option along with a password. The regular zip format with a password isn’t very strong protection any more, there are many programs for cracking this out there.
http://oldhome.schmorp.de/marc/fcrackzip.html
This link covers some of the essentials to get encrypted files with 7zip
http://www.cnx-software.com/2011/02/22/aes-256-encryption-and-file-names-encryption-with-7-zip-7z/
deadlydog
Thanks for the comment. I chose to implement it as zip purely for compatibility reasons, as Windows can now handle .zip files natively, and not everybody knows what a .7z file is. I’ve updated the function to take the compression type as a parameter, so it’s easy to specify to make a 7z file now; zip is still the default though. Thanks :)
Script em Powershell para enviar email com arquivos do DRM | OptimizeTI
[…] Função Zip […]
Script em Powershell para enviar email com arquivos do DRM |
[…] Função Zip […]
SkyBuck
How it’s possible to compress from a UNC path ? I need to compress a folder from my NAS.
Megha
This is still helpful in 2020. Thanks :)
Jazien
2x helpfull in 2020 :)
Holger
Hi, thanks for that function. I only added one feature into the argument syntax. if (!([string]::IsNullOrEmpty($Password))) { $arguments += “ -p$Password” # Header encryption Add -mhe to encrypt headers for 7z files if ($CompressionType -eq “7z”){$arguments += “ -mhe”} }
ConanF
I tried to change $arguments = “a -t$CompressionType ““$ZipOutputFilePath”” ““$FilesToZip”” -mx9” to $arguments = “a -t$CompressionType ““$ZipOutputFilePath”” ““$FilesToZip”” -mhe” -mhe means Encrypts archive header (This will hide the file names inside the archive) However, -mhe was not working at all. I tried in CMD, -mhe was working perfect with outprint below:
7z a -t7z Auto7Zip.7z Auto7Zip.ps1 -p123 -mhe
7-Zip 19.00 (x64) : Copyright (c) 1999-2018 Igor Pavlov : 2019-02-21 Scanning the drive: 1 file, 2853 bytes (3 KiB) Creating archive: Auto7Zip.7z Add new data to archive: 1 file, 2853 bytes (3 KiB) Files read from disk: 1 Archive size: 1520 bytes (2 KiB) Everything is Ok
Why -mhe not working in this function?
Don
is there an argument to set the archive size for a multiple file archive set for large folder zips. say a folder with 3GB data in it but wanted to break it into multiple 200MB files
sadasiva
7z is created but while extraction it shows test folder[has atual files] inside .7z
Leave a Comment
Your email address will not be published. Required fields are marked *