Automated Backups With the Help of Windows Scripting

I’m sure you do not need to be reminded yet again of the importance of backing up your data. Windows provides a fairly capable program to handle this (ntbackup), but who can remember to do this regularly? This article will describe how to go beyond the basic scheduling of backups by using Windows Scripting to solve some problems.

Introduction

I’ve long understood and advocated the importance of regular backups. Basically, I don’t – and never will – trust the hard drive in my computer. I’ve lost a few of them over the years, and even though I’ve been doing backups right from the beginning, I’ve learned the hard way each time that there were additional files that should have been backed up.

I’ve managed to refine my list of necessary items, here’s my list:

  • My documents
  • My email
  • My pictures
  • My Internet bookmarks
  • My web applications
  • Game save files

You may have others such as invoices or browser customizations (ie: FireFox extensions). It’s helpful to make yourself a list.

Once you have that list, Windows 2000 and XP both provide the functionality you need to regularly backup the data. You can do this fairly simply through ntbackup.exe and Scheduled Tasks. However, as I did, you may find these two insufficient to fit your needs.

Here’s the situation I had, and it’s a pretty common one: I used Outlook for my email. This was great for backups, because my entire mail hierarchy was kept in one OST file. However, there was a huge problem. If Outlook was running when the scheduler tried to run the backup task, Outlook would hold onto the OST file, and the backup would fail. It would have been an enormous pain to try to remember to close Outlook in time for every backup. This could end up happening with any possible file you want to back up that is regularly kept open by an application.

I also had a second hard drive that I wanted the backup file copied to for replication, to prevent problems if the first hard drive crashed. Also, I wanted an easy to read log file, that would keep my up to date on the backup status, without me having to search through the event log.

To solve these issues I came up with a very handy VBScript that I’d like to share with you. But first things first, we have to use ntbackup to generate the necessary BKS file.

{mospagebreak title=Pick a File, Any File}

The first thing we need to do is turn the list of wanted files into a list that ntbackup can understand.  What better way to do that could there be than to use ntbackup itself? So go ahead, click Start > Run…. Type ‘ntbackup.exe’.

When the initial screen comes up, switch to ‘Advanced Mode’. Click the ‘Backup’ tab, and you should be at a screen like this:

Automated Backups With the Help of Windows Scripting

Go through your list and check off all the folders that you decided you need to have backed up. But don’t do the backup! Not yet at least. We’re just going to save the selection list for now. To do that, click Job > Save Selections.

This part is important: instead of saving the list in the default directory (C:Documents and SettingscanjxcLocal SettingsApplication DataMicrosoftWindows NTNTBackupdata), we’re going to place it in our own folder. Whatever folder you choose to create (such as c:backup), this will be the folder we place everything in, to make our script easier to configure, and more portable.

So you’ve saved the selection file, let’s move on to the actual script.

{mospagebreak title=The Script}

You’re ready to write the script. Create a VBScript file in c:backup, or whatever you called the folder. If you’re not sure how to do this, it’s as simple as creating a text file, and changing its extension to ‘.vbs’ instead of ‘.txt’. You can call it whatever you want, but backup.vbs will suffice. Here are the lines of the script, with explanations:

Dim objShell, objFSO, thisDir, bksFile, bkfFile, strBackup, strLogFile, objWrite
dim objFile, secondDrive, doCopy, strOutlook

Here I’ve dimensioned all my variables. This is just good practice for a non-lazy coder.

set objFSO = CreateObject( “Scripting.FileSystemObject” )
Set objShell = CreateObject( “Wscript.Shell” )

We are working with two object, the FileSystemObject, and the Shell object. I have created them here.

thisDir = objFSO.GetFolder( objFSO.GetParentFolderName( WScript.ScriptFullName ) ) & “”

This line (there should be no line break) retrieves the name of the folder that you’ve keeping the backup files in. We could have simply coded in “c:backup” as the value of the string, and this might even save a small amount of overhead. However, this is a bad idea if you wish the script to be easily portable, or if the folder name changes down the road. This prevents anyone from having to modify the script.

bksFile = “backup.bks”

bkfFile = “backup.bkf”
strLogFile = “backup_log.txt”

Here I’ve supplied the name of the Backup Selection file that we created. The second file, the bkfFile, is the actual backup file that will be generated by the process. The third file is clearly the backup log we will create.

strBackup = “ntbackup backup “”@” & thisDir & bksFile & “”” /f “”” & _

thisDir & bkfFile & “”””

This is an important line. This is the line we will run the backup with. If you wish to modify the process further with extra ntbackup options, this is the line you would edit. To understand what all the extra options are, open the Run prompt, and type ‘ntbackup /?’.

secondDrive = “f:bkp”

doCopy = true

If you wish to replicate the backup file, this is your opportunity. You specify the location to copy the backup file to, and just set the boolean marker whether or not to actually copy it. Now I’ll handle the whole Outlook issue. You can modify the next piece to fit whatever application you need to.

strOutlook = “””C:Program FilesMicrosoft OfficeOffice10OUTLOOK.EXE”” /recycle”

objShell.Run strOutlook

wScript.Sleep(4000)

objShell.AppActivate( “outlook” )

wScript.Sleep(4000)

objShell.SendKeys( “%{F4}” )

So the first line is there to open Outlook. With the ‘recycle’ option, this prevents the system from just opening another instance of Outlook if it’s already open. If it’s not open, it will be, and this prevents any errors in the script when it tries to close it. We set the script to sleep, or pause for 4 seconds, which should be sufficient time for your system to open it. You can modify this if you have a slower or faster machine. Then the AppActivate line brings Outlook into application focus, (the forefront window) which is important for the SendKeys line. The SendKeys line passes “%{F4}” to the focused application, which is the equivalent of pressing Alt + F4, which you know closes a Windows program. At the end of that chunk, we should have successfully closed Outlook (or whatever your mail application is), thus releasing its hold on your mail files.

objShell.Run strBackup, 1, true

Here we run the backup, simple as that.

If Not objFSO.FileExists( strLogFile ) Then objFSO.CreateTextFile( strLogFile )

set objWrite = objFSO.OpenTextFile( strLogFile, 8 )

Set objFile = objFSO.GetFile( thisDir & bkfFile )

objWrite.WriteLine( Date() & ” – backup file is: ” & objFile.Size & ” bytes”)

objWrite.Close()

In this little section, we create the log file if it isn’t there yet, and open it for writing. I’ve decided that in my log I want to know the date of the last backup, and the size of the backup file at the time. You may want more information, that’s up to you.

if doCopy then objFile.Copy secondDrive, True

Here’s where the replication takes place. And after which, we’ll do the final cleanup.

Set objShell = Nothing
Set objFSO = Nothing
Set objWrite = Nothing
set objFile = Nothing
msgBox( “Backup Successful ” & date() )

You might want this line, you might not. Somehow I find it comforting to look at my computer in the morning, and have a friendly little box telling me that everything is OK.

{mospagebreak title=Work Out a Schedule}

The last step you need to take is to put the backup script on a schedule. You can do this by going to your Control Panel, and clicking ‘Scheduled Tasks’. Then click ‘Add scheduled Task’.

When the first screen of the wizard pops up, click ‘Next’. The wizard will present you with a long list of programs you can choose from. Just click ‘Browse’, and find the Backup.vbs file that you created. Choose the schedule you wish (I run mine twice weekly). You may need to supply credentials, the username and password under which the task will run. You will need to supply administrator level permissions, or better yet ‘Backup Operator’. If you only supply user level permissions, the script will more than likely fail.

Conclusion

This is an extremely useful way to automate your backups. As I mentioned in the outset, you could simply use ntbackup and the scheduler, but this will more than likely be insufficient for your needs, as it was for mine. Every so often it’s a good idea to burn the backup file to CD, or whatever other means external storage you have. I hope this script will make your life as easy as it has mine! Here’s the full script:

Dim objShell, objFSO, thisDir, bksFile, bkfFile, strBackup, strLogFile, objWrite
dim objFile, secondDrive, doCopy, strOutlook

set objFSO = CreateObject( “Scripting.FileSystemObject” )
Set objShell = CreateObject( “Wscript.Shell” )
thisDir = objFSO.GetFolder( objFSO.GetParentFolderName( WScript.ScriptFullName ) ) & “”

bksFile = “backup.bks”
bkfFile = “backup.bkf”

strBackup = “ntbackup backup “”@” & thisDir & bksFile & “”” /f “”” & thisDir & bkfFile & “”””
strLogFile = “backup_log.txt”
strOutlook = “””C:Program FilesMicrosoft OfficeOffice10OUTLOOK.EXE”” /recycle”

secondDrive = “f:bkp”
doCopy = true

‘=== close Outlook
objShell.Run strOutlook
wScript.Sleep(4000)
objShell.AppActivate( “outlook” )
wScript.Sleep(4000)
objShell.SendKeys( “%{F4}” )

‘=== perform backup
objShell.Run strBackup, 1, true

‘=== log backup
If Not objFSO.FileExists( strLogFile ) Then objFSO.CreateTextFile( strLogFile )
set objWrite = objFSO.OpenTextFile( strLogFile, 8 )
Set objFile = objFSO.GetFile( thisDir & bkfFile )

objWrite.WriteLine( Date() & ” – backup file is: ” & objFile.Size & ” bytes”)
objWrite.Close()

‘=== copy backup file
if doCopy then objFile.Copy secondDrive, True

‘=== cleanup
Set objShell = Nothing
Set objFSO = Nothing
Set objWrite = Nothing
set objFile = Nothing

msgBox( “Backup Successful ” & date() )

9 thoughts on “Automated Backups With the Help of Windows Scripting

  1. Hi Justin,

    It was really good script.
    Earlier i used to do backup using ntbackup, now your article made me to think differently.

    Keep it up

    Rgds,
    Surjit

  2. Hi Justin,

    Your code closing outlook(already opened) worked fine.
    I tried to open outlook using script, then suddenly outlook puked error message box “Not able to find some dll related to VirusScan”. User need to press OK Button of msg box to start outlook.

    So how should i handle this situation using WSH.

    Your suggestions/help much appreciated.

    Rgds,
    Surjit

  3. I have never seen this error before
    You could send another keystroke, maybe the spacebar, and that would close the prompt, then send the alt f4 keystroke

  4. I get the following error when running this script:

    Script: c:\temp\backup.vbs
    Line: 31
    Char: 1
    Code: 800A0035
    Source: Microsoft VBScript runtime error

  5. I believe it is this line:

    Set objFile = objFSO.GetFile( thisDir & bkfFile )

    I just took the entire code from the last page of the article and pasted it into my file, using notepad.

  6. Delete the extend.dat file inside the user profile folder to solve the problem when starting outlook.

    More Info here:
    http://support.microsoft.com/d

    It is the same solution for every extension for outlook. The extension was uninstalled or it does not exist in the registry, but it is still cached in extend.dat

[gp-comments width="770" linklove="off" ]