Tuesday, March 26, 2019

7Zip Command Line Random File Name

I need to make backups of a database every hour.  I spent a little too much time coming up with my simple solution, so passing it on here to save you the time.

My goal was to run a Windows batch file that will simply pack up certain files into a zip archive, give the archive a random name so it won't overwrite other archives, and apply password encryption to the archive.

Here's how I call 7zip from the Windows command line to do what I need.

7z.exe a -tzip -p"Password" %random%.zip *.db

What it means

7z.exe, call 7zip from command line
a,  add files
-tzip, use zip compression
-p"Password",  encrypt using Password as the password.  Yes, you need to use the quotations.
%random%.zip,  pulls a random number from the Windows shell, use it as a file name and append .zip to it.
*.db, pack up all .db files in the folder.

The rest of my project involved copying the encrypted zip file to Dropbox for offsite storage. There are most certainly other perhaps better ways to accomplish this, but maybe none more simple than this. The timestamp on the file makes it simple to spot the most recent file.  In my experience, simple is usually better.

7zip is a fantastic tool capable of doing a lot.  While Googling around, I found posts that focused on formatting date/time for use in a file name.  But in the end, all I really need is a random number.

That's all there is to it!  Now go get some coffee and enjoy the 30 minutes you just saved!

Addendum:

Ok, I wanted to add this here, if only for my own future use. Sathyajith Bhat had a great answer elsewhere that showed me how to put the current date into the archive file name with 7zip. Try this:

7z -tzip -aou -p"Password" "%DATE:~7,2%.%DATE:~4,2%.%DATE:~-4% Backup".zip *.db

This will create a file named something like:     26.03.2019 Backup.zip
Using Bhat's string extraction tip, you can do all kinds of other things.