I’ve been looking for a way to password protect a csv file but found it’s not possible natively so one way to encrypt it is to zip it first and password protect the zip file.
Now I have multiple files I want to to zip using 7-Zip compression and again I’ve been googling my brains out looking for the correct search terms and eventually landed on this answer so here’s how I applied it to my Powershell script…
First make sure you have 7-Zip installed on your computer. Then take note of the 7z.exe file
Note that this example is for static files or individual files you can specify directly. This is not for dynamic files or all files in a folder. I’ll get to that in time hehe
Here’s the code that creates a random password, defines the csv files to zip, and creates a password protected zip file by passing the filenames as arguments
## -- Creating Random Password -- ## [Reflection.Assembly]::LoadWithPartialName("System.Web") $randomPassword = [System.Web.Security.Membership]::GeneratePassword(8,2) ## -- Files to zip -- ## $csvFile = "D:\csvFile1.csv" $csvFile2 = "D:\csvFile2.csv" ## -- Creating Zip File -- ## $zipOutputFilePath = "D:\ZipOutputFile.zip" $pathTo64Bit7Zip = "C:\Program Files\7-Zip\7z.exe" $arguments = "a -tzip ""$ZipOutputFilePath"" ""$csvFile"" ""$csvFile2"" -mx9 -p$randomPassword" $windowStyle = "Normal" $p = Start-Process $pathTo64Bit7Zip -ArgumentList $arguments -Wait -PassThru -WindowStyle $windowStyle $zipped = $ZipOutputFilePath
After execution your zip file should ask for a password before extracting.