Error DataBase-One Place all Solutions Forums Blog Glossary    Contact Us
Search  
   
Browse by Category
Error DataBase-One Place all Solutions .: Operating Systems .: Windows Operating Systems .: Windows Scripts and Batch Files .: VB Script to Run NTBackup from VBScript and save backup to SNAP Server

VB Script to Run NTBackup from VBScript and save backup to SNAP Server

Important Notes


SNAP Server Share must exist and be online before Script is run, Example: 192.168.0.201\ShareName\
The Email folder \\192.168.0.201\ShareName\Email\ must exist before script is run

Backup Selection must be created in NTBackup before script is run and placed in the BackupRootFolder - Example:
\\192.168.0.201\ShareName\UsersFolder.bks

To change the files that are included in the backup - Open NTBackup, select the files, Save the selection as a .BKS file
in the BackupRootFolder, give the file an appropriate name and assign that name to the variable NTBackupRootFolder
below.

ONLY CHANGE THE NON-CONSTANT VARIABLES BELOW

This script was designed to run on Windows 2003 server, if it is used on windows 2000 then change the line

CHR(34) & " /L:f /M " & JobType & " /SNAP:on", 0, True)

to

CHR(34) & " /L:f /M " & JobType, 0, True)

because windows 2000 does not have the /SNAP:on switch in NTBackup

Change the NON-Constant variables below to suit your network, the script will be run as a scheduled task on the server to be backed up under a users credentials that has both access rights to the SNAP server and "Backup and Restore" rights on the server. The script will then email the log to a given email address. The Server will require an internet connection for the email.

The script creates a folder for each days backup, if the SNAP server is full then the script will search for the oldest backup file in the Saturday folder and delete it, givning more room for another backup, however it does not search other folders, this was sufficient for me. if you find that your SNAP server is full and no files exist in the saturday folder then the log will be 0 bytes in the email, at this point you should manually delete a backup file.

'Start of Script ---------------------------------------------------------------------------------------------------------------------

Option Explicit

'On Error Resume Next

'Define Variables
Dim FileDelete, Fso, FSOFileExists, CreateLogFile, NTBackuplogFileName, BackupTempLogData, LogsFolder, NTBackupFolder
Dim IfFileExists, NTBackupTempLog, BackupTempLog, objFileHandle, Todaysdate, JobName, EventViewer, FinalLog
Dim ObjShl, RunNTBackup, WshShell, StartCMD, StartCMDType, UserProfile, LastTempFile, ArchiveFolder, CurrentTime
Dim JobType, IFFolderExists, CreateNTbackupFolder, CreateLogsFolder, CreateArchiveFolder, FileSelectionFileName
Dim BackupRootFolder, ArchiveLog, RunEmail, EmailFolder, BackupNSServer, DayOfTheWeek, WeekDayVar, BackupFolder
Dim CreateBackupFolder, SMTPServer, SNAPMail, FromAddress, SMTPServerPort, objFso, CopyLog, TempDir, TempDir1, ToAddress

Dim DiskSpace, DriveName, Ready, ClngDiskSpace, IntStrCompare, IntStr1Count, StringLength
Dim FileName, SourceFolder, Folders1, Folder1, Folder2, strDir, Folder3, OldestDate1
Dim FilePath, WSH, CreateFile, OpenFile, DateCreated, OpenFile1, Date1, Date2, Date3
Dim Date4, DateDiffNmbr, Date5, x, ArrayCounter, ViewArray, y, z, OldestDate, ArrayVar
Dim Counter, Var, Var1, Var2, DeleteFileName, Line1, OpenFile2, IntStr1, StringLenth, IntStr2
Dim FileExist, IntStrCompare1, IntCounter1, Run, AverageFileSize, IntStrRev1
Dim IntCounter, AllText, SourceFolderParsed, IntStrDiff, FileNmr, WSHN, Sharename

Set Fso = Createobject("Scripting.FileSystemObject")
Set WSH = WScript.CreateObject("WScript.Shell")
Set WSHN = Wscript.CreateObject("WScript.Network")
TempDir = WSH.ExpandEnvironmentStrings("%Temp%")

ReDim DateArray(0)
ArrayCounter = UBound(DateArray)

' Define Constant Variables
Const TristateFalse = 0

' Format Date as DD_MM_YYYY so that NTBackup.exe can use it in a filename
TodaysDate = Mid(Date, 1, 1) & Mid(Date, 2, 1) & "_" & Mid(Date, 4, 1) & Mid(Date, 5, 1) & "_" & _
Mid(Date, 7, 1) & Mid(Date, 8, 1) & Mid(Date, 9, 1) & Mid(Date, 10, 1)

' Find day if the week and save as variable DayOfTheWeek
WeekDayVar = Weekday(Date)
IF WeekDayVar = 1 Then
DayOfTheWeek = "Sunday"
End If
IF WeekDayVar = 2 Then
DayOfTheWeek = "Monday"
End If
IF WeekDayVar = 3 Then
DayOfTheWeek = "Tuesday"
End If
IF WeekDayVar = 4 Then
DayOfTheWeek = "Wednesday"
End If
IF WeekDayVar = 5 Then
DayOfTheWeek = "Thursday"
End If
IF WeekDayVar = 6 Then
DayOfTheWeek = "Saturday"
End If
IF WeekDayVar = 7 Then
DayOfTheWeek = "Saturday"
End If

'
' -------------------------------------------------------------------------------------------------------------
'
' -------------------------------------------------------------------------------------------------------------
' ONLY CHANGE the white text

'You can use the server DNS names rather than the IP address, it is your choice

' Define Non-Constant Variables
ShareName = "\\ServerIPAddress\ShareName"
BackupFolder = "\\ServerIPAddress\ShareName\NTBackup\"
NTBackupFolder = "\\ServerIPAddress\ShareName\NTBackup\" & DayOfTheWeek & "\"
JobName = "ServerName_" & TodaysDate
ArchiveFolder = "\\ServerIPAddress\ShareName\NTBackup\Archive\"
LogsFolder = "\\ServerIPAddress\ShareName\NTBackup\Logs\"
JobType = "Normal" ' Normal or Incremental or Differential
FileSelectionFileName = "XPSetupFiles.bks"
BackupRootFolder = "\\ServerIPAddress\ShareName\"
EmailFolder = "\\ServerIPAddress\ShareName\Email\"
BackupNSServer = "SNAPServerDNSName "
SMTPServer = "SMTPIPAddressOrDNSName"
SMTPServerPort = "25"
FromAddress = "Backup.User@EmailAddress.com"
ToAddress = "Backup.Mail@EmailAddress.com"

' -------------------------------------------------------------------------------------------------------------
'
' -------------------------------------------------------------------------------------------------------------

Set DriveName = Fso.GetDrive("X:\")
SourceFolder = BackupFolder & "Saturday\"
Folder3 = BackupFolder
IntStrCompare = 1
IntStrCompare1 = 4
IntStr1Count = 1
Counter = 0

WSHN.mapNetworkDrive "X:", Sharename
Ready = DriveName.IsReady
If Ready = True Then
DiskSpace = DriveName.AvailableSpace
End If
WSHN.RemoveNetworkDrive "X:", True

'-------------------------------------------------------------------------------------------------------

StringLength = Len(SourceFolder)

IntStrRev1 = InstrRev(SourceFolder, CHR(92), StringLength, 1)

DriveName = Mid(SourceFolder, 1, 1)

For IntCounter = 1 to 100

If IntStr1 = IntStrRev1 Then
IntCounter = 100
End If

IntStr1 = Instr(IntStrCompare, SourceFolder, CHR(92), 1)
IntStr2 = Instr(IntStrCompare1, SourceFolder, CHR(92), 1)
IntStrCompare = IntStr1 + 1
IntStrCompare1 = IntStr2 + 1
IntStrDiff = IntStr2 - IntStr1
If IntStrDiff < 0 Then
IntStrDiff = 2
End If
If IntStrCompare1 > StringLength Then
IntCounter = 100
End If
If IntStr1 = "" Then
IntStr1 = ""
IntCounter = 100
Else
IntStr1Count = IntStr1Count + 1
End If
If IntStr2 = "" Then
IntStr2 = StringLength
End If

Var1 = Mid(Sourcefolder, IntStrCompare, IntStrDiff - 1)

Var2 = Var2 & ".SubFolders(" & CHR(34) & Var1 & CHR(34) & ")"

SourceFolderParsed = "FSO.Drives(" & CHR(34) & DriveName & ":" & CHR(34) & ").RootFolder"

Next

SourceFolderParsed = SourceFolderParsed & Var2 & ".Files"

Set CreateFile = FSO.CreateTextFile(TempDir & "\00TempFile.vbs", True)
With CreateFile
.Writeline "Dim FsoFiles, Counter, Counter1, FileNames, SourceFolder"
.WriteLine "Dim FName, FSO, FileSize, TestVar, File1, TotalFileSize, CreateFile"
.WriteBlankLines(1)
.WriteLine "Set FSO = CreateObject(" & CHR(34) & "Scripting.FileSystemObject" & CHR(34) & ")"
.WriteLine "SourceFolder = " & CHR(34) & SourceFolder & CHR(34)
.WriteBlankLines(1)
.WriteLine "Set FSOFiles = " & SourceFolderParsed
.WriteBlankLines(1)
.WriteLine "Counter1 = FSOFiles.Count"
.WriteLine "Counter = FSOFiles.Count"
.WriteBlankLines(1)
.WriteLine "Redim FileNames(counter-1)"
.WriteBlankLines(1)
.WriteLine "for each file in FSOFiles"
.WriteLine "Fname = lcase(Fso.GetFileName(file.name))"
.WriteLine "counter = counter - 1"
.WriteLine "FileNames(counter) = ucase(file.name)"
.WriteLine "Set File1 = FSO.GetFile(SourceFolder & FName)"
.WriteLine "FileSize = file1.Size"
.WriteLine "TotalFileSize = TotalFileSize + FileSize"
.WriteLine "next"
.WriteLine "Set CreateFile = FSO.CreateTextFile(" & CHR(34) & TempDir & "\TotalFileSize1.tmp" & CHR(34) & ", True)"
.Writeline "CreateFile.WriteLine TotalFileSize"
.WriteLine "CreateFile.WriteLine Counter1"
.WriteLine "WScript.Quit"
.Close
End With

WScript.Sleep 1000

Run = WSH.Run(TempDir & "\00TempFile.vbs", 0, True)

WScript.Sleep 1000

FileDelete = FSO.DeleteFile(TempDir & "\00TempFile.vbs", True)

Set OpenFile = Fso.OpenTextFile(TempDir & "\TotalFileSize1.tmp", 1)
AllText = OpenFile.ReadLine
FileNmr = OpenFile.ReadLine
OpenFile.Close

AverageFileSize = AllText / FileNmr

'---------------------------------------------------------------------------------------------------------

Do While AverageFileSize > DiskSpace
Set CreateFile = FSO.CreateTextFile(TempDir & "\00TempFile1.tmp", True)
CreateFile.Close

Set Folders1 = FSO.GetFolder(Folder3)
For Each Folder2 in Folders1.Subfolders

GetDir SourceFolder

Next

'Openfile and counter the number of entries - if odd then add todays date
Set OpenFile1 = FSO.OpenTextFile(TempDir & "\00TempFile1.tmp", 1)
Do While OpenFile1.AtEndOfStream = False
Counter = Counter + 1
OpenFile1.SkipLine
Loop
OpenFile1.Close

Var = Counter / 2

Var1 = Fix(var)

Var2 = Var - Var1

If Var2 < 1 AND Var2 > 0 Then
Set OpenFile1 = FSO.OpenTextFile(TempDir & "\00TempFile1.tmp", 8)
OpenFile1.WriteLine Date
OpenFile1.Close
End If

On Error Resume Next
'Open 00TempFile1.tmp and get oldedest date
Set OpenFile1 = FSO.OpenTextFile(TempDir & "\00TempFile1.tmp", 1)
Do While OpenFile1.AtEndOfStream = False
Date1 = OpenFile1.Read(10)
Date2 = Replace(Date1, "_", "/", 1)
OpenFile1.SkipLine
Date3 = OpenFile1.Read(10)
Date4 = Replace(Date3, "_", "/", 1)
OpenFile1.SkipLine
DateDiffNmbr = DateDiff("d", Date2, Date4)
If DateDiffNmbr < 0 Then
Date5 = Date4
Else
Date5 = Date2
End If

On Error Resume Next
DateArray(ArrayCounter) = Date5
On Error Goto 0
ArrayCounter = ArrayCounter + 1
ReDim Preserve DateArray(ArrayCounter)

Loop
On Error Goto 0

ReDim Preserve DateArray(UBound(DateArray) - 1)

x = 0
y = 1
Do While x < (UBound(DateArray) - 1)

Date1 = DateArray(x)
Date2 = DateArray(y)
DateDiffNmbr = DateDiff("d", Date1, Date2)

If DateDiffNmbr < 0 Then
DateArray(x) = DateArray(UBound(DateArray))
Else
DateArray(y) = DateArray(UBound(DateArray))
End IF

ReDim Preserve DateArray(UBound(DateArray) - 1)
ArrayVar = 0
Date1 = ""
Date2 = ""
DateDiffNmbr = ""

If UBound(DateArray) = 1 Then
Date1 = DateArray(0)
Date2 = DateArray(1)
DateDiffNmbr = DateDiff("d", Date1, Date2)
If DateDiffNmbr < 0 Then
OldestDate = Date2
Else
OldestDate = Date1
End IF
Date1 = ""
Date2 = ""
End If

Loop

Erase DateArray

Oldestdate1 = Replace(OldestDate, "/", "_", 1)
Set OpenFile2 = FSO.OpenTextFile(TempDir & "\00TempFile1.tmp", 1)
Do While OpenFile2.AtEndOfStream = False
Line1 = OpenFile2.ReadLine
IntStr1 = InStr(1, Line1, OldestDate1, vbTextCompare)
If IntStr1 > 0 Then
IntStr2 = InStr(1, Line1, ",", vbTextCompare)
DeleteFileName = Mid(Line1, IntStr2 + 1)
End If
Line1 = ""
Loop
OpenFile2.Close

FileExist = FSO.FileExists(DeleteFileName)
If FileExist = True Then
If AverageFileSize > DiskSpace Then
FileDelete = FSO.DeleteFile(DeleteFileName, True)
End If
End If
Loop

' SCript Execution
On Error Resume Next

Set Fso = CreateObject("Scripting.FilesystemObject")
IFFolderExists = Fso.FolderExists(BackupFolder)
IF IFFolderExists = False Then
CreateBackupFolder = Fso.CreateFolder(BackupFolder)
CreateNTbackupFolder = Fso.CreateFolder(NTBackupFolder)
CreateLogsFolder = Fso.CreateFolder(LogsFolder)
CreateArchiveFolder = Fso.CreateFolder(ArchiveFolder)
Create
End IF

' Delete all Backup log files.
'On Error Resume Next
Set Fso = CreateObject("Scripting.FileSystemObject")
FileDelete = Fso.DeleteFile(NTBackupFolder & "Logs\" & "*.*")
'On Error Goto 0

' Create Log File
Set Fso = CreateObject("Scripting.FileSystemObject")
Set CreateLogFile = Fso.CreateTextFile(LogsFolder & "Temp_" & JobName & ".log", True, TristateFalse)
With CreateLogFile
.WriteLine "Temp Log file for Backup Job " & JobName & ".bkf"
.WriteBlankLines(1)
CurrentTime = Now
.WriteLine JobName & "Started: " & VbTab & CurrentTime
.WriteBlankLines(1)
.Close
End With

WScript.Sleep 2000

' NTBackup Temp Log file will now be reffered to as BackupTempLog
BackupTempLog = LogsFolder & "Temp_" & JobName & ".log"

' Delete all NTBackup files in NTBackup folder - if none exist resume script execution
'On Error Resume Next
FileDelete = Fso.DeleteFile(NTBackupFolder & "*.bkf") ' Change this to only delete files if number of files > 4
'On error Goto 0

' Set up access to %Temp variable%
Set WshShell = WScript.CreateObject("WScript.Shell")
UserProfile = WshShell.ExpandEnvironmentStrings("%UserProfile%") & CHR(92)

' Delete all NTBackup log files.
'On Error Resume Next
FileDelete = Fso.DeleteFile(UserProfile & "\Local Settings\Application Data\Microsoft\Windows NT\NTBackup\data\" & "*.log")
'On Error Goto 0

' Run NTBackup and backup Folder
set ObjShl = WScript.CreateObject("WScript.Shell")
RunNTBackup = ObjShl.Run("NTBackup.exe backup @" & BackupRootFolder & FileSelectionFileName & " /j " & CHR(34) & "NTBackup_" & _
TodaysDate & CHR(34) & " /f " & CHR(34) & NTBackupFolder & "NTBackup_" & TodaysDate & "_" & JobType & ".bkf " & _
CHR(34) & " /L:f /M " & JobType & " /SNAP:on", 0, True)

' Get Backup Job Log filename
NTBackuplogFileName = Fso.MoveFile(UserProfile & "\Local Settings\Application Data\Microsoft\Windows NT" & _
"\NTBackup\data\*.log", LogsFolder)

WScript.Sleep 2000

' Start CMD and rename NTBackup log file
StartCMD = ObjShl.Run("%Comspec% /C Rename " & LogsFolder & "Backup*.log NTBackup_Temp_" & _
JobName & ".log", 0, True)
' NTBackup lof file now referred to as TempLog
NTBackupTempLog = LogsFolder & "NTBackup_Temp_" & JobName & ".log"

Wscript.Sleep 3000

' Create Final Log
Set ObjFileHandle = Fso.CreateTextFile(LogsFolder & JobName & "_" & JobType & ".log", True, TriStateFalse)
FinalLog = LogsFolder & JobName & "_" & JobType & ".log"

WSCript.Sleep 1000

' Run Type command and create new log file that can be read by vbscript
StartCMDType = ObjShl.Run("%Comspec% /C Type " & NTBackupTempLog & " > " & NTBackupTempLog & ".temp", 0, True)

LastTempFile = NTBackupTempLog & ".temp"

WScript.Sleep 4000

Set ObjFileHandle = Fso.OpenTextFile(LastTempFile, 1)
BackupTempLogData = objFileHandle.ReadAll
objFileHandle.Close
Set ObjFileHandle = Fso.OpenTextFile(FinalLog, 2)
ObjFileHandle.WriteLine "Backup Log for Job: " & vbTab & JobName & ".bkf"
ObjFileHandle.WriteBlankLines(2)
ObjFileHandle.WriteLine BackupTempLogData
ObjFileHandle.WriteBlankLines(2)
ObjFileHandle.WriteLine JobName & " Complete: " & DayOfTheWeek & vbTab & CurrentTime
ObjFileHandle.Close
'End If

WScript.Sleep 3000

' Check for existence of log file
IfFileExists = Fso.FileExists(FinalLog)
If IfFileExists = False Then
Set EventViewer = WScript.CreateObject("WScript.Shell")
EventViewer.LogEvent 1, "VBScript BackupJob " & JobName & "Error - Log File was not Created."
End If

' Copy Final Log to Archive folder
Set Fso = CreateObject("Scripting.FileSystemObject")
ObjFileHandle = Fso.CopyFile(FinalLog, ArchiveFolder)

WScript.Sleep 2000

' Delete all Backup log files.
'On Error Resume Next
Set Fso = CreateObject("Scripting.FileSystemObject")
FileDelete = Fso.DeleteFile(LogsFolder & "*.*")
'On Error Goto 0

' Email file to Backup Mail
ArchiveLog = ArchiveFolder & JobName & "_" & JobType & ".log"

Set WshShell = CreateObject("WScript.Shell")
TempDir1 = WshShell.ExpandEnvironmentStrings("%Temp%")
TempDir = TempDir1 & "\"

Set objFso = CreateObject("Scripting.FileSystemObject")
CopyLog = objFso.CopyFile(ArchiveLog, TempDir, True)

Set SNAPMail = CreateObject("CDO.Message")
SNAPMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
SNAPMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = SMTPServer
SNAPMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = SMTPServerPort
SNAPMail.Configuration.Fields.Update
SNAPMail.Subject = "Backup Log for " & JobName
SNAPMail.From = FromAddress
SNAPMail.To = ToAddress
SNAPMail.TextBody = "if " & FinalLog & " is not attached, you can find it at: " & vbCrLf & vbCrLf & ArchiveLog & vbCrLf
SNAPMail.AddAttachment TempDir & FinalLog
SNAPMail.Send

 

Function GetDir(strDir)
Dim File, Folder, Folder1
strDir = Folder3 & Folder2.Name

Set Folder = FSO.GetFolder(strDir)
For each File in Folder.Files
FileName = File.Name
DateCreated = Mid(FileName, 10, 10)
FilePath = File.Path
Set OpenFile = FSO.OpenTextFile(TempDir & "\00TempFile1.tmp", 8, False, 0)
OpenFile.WriteLine datecreated & "," & FilePath
OpenFile.Close
Next

For Each Folder1 in Folder.SubFolders
GetDir(Folder1.path)
Next

End Function

Set DiskSpace=Nothing
Set DriveName=Nothing
Set Ready=Nothing
Set ClngDiskSpace=Nothing
Set IntStrCompare=Nothing
Set IntStr1Count=Nothing
Set StringLength=Nothing
Set FSO=Nothing
Set FileName=Nothing
Set SourceFolder=Nothing
Set Folders1=Nothing
Set Folder1=Nothing
Set Folder2=Nothing
Set strDir=Nothing
Set Folder3=Nothing
Set OldestDate1=Nothing
Set FilePath=Nothing
Set TempDir=Nothing
Set WSH=Nothing
Set CreateFile=Nothing
Set OpenFile=Nothing
Set DateCreated=Nothing
Set OpenFile1=Nothing
Set Date1=Nothing
Set Date2=Nothing
Set Date3=Nothing
Set Date4=Nothing
Set DateDiffNmbr=Nothing
Set Date5=Nothing
Set x=Nothing
Set ArrayCounter=Nothing
Set ViewArray=Nothing
Set y=Nothing
Set z=Nothing
Set OldestDate=Nothing
Set ArrayVar=Nothing
Set Counter=Nothing
Set Var=Nothing
Set Var1=Nothing
Set Var2=Nothing
Set DeleteFileName=Nothing
Set Line1=Nothing
Set OpenFile2=Nothing
Set IntStr1=Nothing
Set StringLenth=Nothing
Set IntStr2=Nothing
Set FileExist=Nothing
Set FileDelete=Nothing
Set IntStrCompare1=Nothing
Set IntCounter1=Nothing
Set Run=Nothing
Set AverageFileSize=Nothing
Set IntStrRev1=Nothing
Set IntCounter=Nothing
Set AllText=Nothing
Set SourceFolderParsed=Nothing
Set IntStrDiff=Nothing
Set FileNmr=Nothing
set WshShell=nothing
set objFso=nothing
set SNAPMail=nothing
Set TodaysDate = Nothing
Set BackupFolder = Nothing
Set NTBackupFolder = Nothing
Set JobName = Nothing
Set ArchiveFolder = Nothing
Set LogsFolder = Nothing
Set JobType = Nothing
Set FileSelectionFileName = Nothing
Set BackupRootFolder = Nothing
Set EmailFolder = Nothing
Set BackupNSServer = Nothing
Set SMTPServer = Nothing
Set SMTPServerPort = Nothing
Set FromAddress = Nothing
Set Fso = Nothing
Set BackupTempLog = Nothing
Set StartCMD = Nothing
Set StartCMDType = Nothing
Set ObjFileHandle = Nothing
Set objFso = Nothing
Set SNAPMail = Nothing
Set ArchiveLog = Nothing
Set TempDir1 = Nothing
Set TempDir = Nothing

On Error Goto 0


How helpful was this article to you?

Related Articles

article How to backup Exchange 2003 with NTBACKUP
One of the most important tasks for an...

(No rating)  4-1-2008    Views: 175   
article How to backup Exchange 2000 with NTBACKUP
One of the most important tasks for an...

(No rating)  4-1-2008    Views: 170   
article How to Remotely manage Windows 2008 Server Core Settings through MMC Snap-ins
Windows Server 2008, Server Core...

(No rating)  3-26-2008    Views: 211   

User Comments

Add Comment
No comments have been posted.