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.