PowerShell – Zip Folder and Email

When working with files and folders, one of the things we do often is zip (compress) them, either for smaller archives or possibly to send as an attachment via email. In this short post, I’ll show how we can use 7-zip to compress a folder and email it using PowerShell.

Why use 7-zip? I’ve seen other ways to zip folders using PowerShell but most dive further into .Net than I am comfortable with. 7-zip is a free application with most every bell and whistle you could ask for. It is extremely easy to work with and can be distributed on servers (or desktops) at will.

The script below does require that 7-zip be installed on the system it is used on.
Once 7-zip is installed there is a command line portion of the help file that can be used to tweak the command needed to get your desired results. In the example below I am zipping a folder ($TheFolder) while excluding a sub-folder ($fExclude) and the resulting file will be $outfile. There are two things to notice about the current $outfile. First as you can probably see, is that it appends the $theDate and $theTime to the file name. Secondly it does not use the default file extension (.7z) and instead uses .bak. The reasoning for this is to avoid email filters stripping our attachment.

Be sure to adjust all the user variables for your needs.

# Simple Backup to Email script
# Requirements: 7-Zip to be installed
# User Variables
# Folder to zip and send
$TheFolder = "E:\ZipMe"
# (sub)Folder to exclude
$fExclude = "SkipMe"
# Path to zip file (output)
$theDay = Get-Date Format "MMddyyyy"
$theTime = Get-Date Format "HHmmss"
$outfile = "E:\zippedfolder_$theDay$theTime.bak"
# Path to 7-zip
$7z = "E:\Program Files\7-Zip\7z.exe"
# 7-zip Arguments
$7zArgs = "a", "$outfile", "$TheFolder", "-xr!$fExclude"
# Email setup
$emailsubject = "Archive – " + $TheFolder + " – Rename file extension to .7z"
$sendTo = "youraddy@whoever.com"
$sendFrom = "sender@whoever.com"
$smtpserver = "your.relay.com"
# End User Variables
# Zip it up and save 7z output as email msg body
[string]$Body = & $7z $7zArgs
# Send output to email
send-mailmessage to $sendTo from $sendFrom Subject $emailsubject smtpserver $smtpserver Body $Body Attachments $outfile
#Remove zip file
Remove-Item $outfile

view raw
Zip2Email.ps1
hosted with ❤ by GitHub

Leave a Reply

Your email address will not be published. Required fields are marked *