Creating backup zips on the fly with bat script and Powershell

Yes, I know… There are thousands ways to do this and even a thousands programs, helpers scripts and/or repositories. And yes, every serious project should have a decent backup system etc. etc. But, this is for all those little projects you are testing out. Trying if it works, copy/paste the whole folder over and over again, seems faster than setting up a proper backup system on the server (it’s not… in the long run). But until your little project gets his feet of the ground, here is a little ‘one click script’ to backup your old data on a daily basis.

Solution:

Ok, as you can see, this creates a date folder and puts the zipped data there. And yes, you should mind the datetime format on the system, and yes it can overwrite your data when used multiple times a day, but if you have that problem, then you don’t need this script. You need to get more serious and use something more professional


@ECHO OFF

SETLOCAL EnableDelayedExpansion

    for /f "skip=1 tokens=1-6 delims= " %%a in ('wmic path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') do (
        IF NOT "%%~f"=="" (
            set /a FormattedDate=10000 * %%f + 100 * %%d + %%a			
            set FormattedDate=!FormattedDate:~0,4!!FormattedDate:~4,2!!FormattedDate:~6,2!
        )
    )

SET SourceDirPath=E:\
SET SFolderName=XCC
SET SourceDirPath=%SourceDirPath%%SFolderName%

SET DestinationDirPath=E:\Bckp\

mkdir %DestinationDirPath%%FormattedDate%

powershell.exe -nologo -noprofile -command "& { Add-Type -A 'System.IO.Compression.FileSystem';[IO.Compression.ZipFile]::CreateFromDirectory('%SourceDirPath%', '%DestinationDirPath%%FormattedDate%\%SFolderName%.zip');}"


Output:

Anything in your “SFolderName” gets zipped and that zip is in today’s DestinationDirPath yyyymmdd folder.

Warning! This script works only with .net framework 4.5.1 or higher. Sorry dudes, need to update those things anyway. One more reason to do so!

Leave a Reply

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