Jump to content

Backup Script please look over


Recommended Posts

Working on a backup script that copies the files in a specific directory on a daily basis and also a monthly basis (all files for the month). During the monthly backup it orginizes the files at the same time by moving them into a directory for that month. These are kept for 1 year. I have 5 logs, 1 log is just a list of all files in that directory, another is an error log of failed filecopies, a flag log that sets flags for copy and move of the file, a copy log which just tracks all files that were copied and where they were copied to, and a move log of all files that were moved and where they were moved to.

This actually backs up to DVD. There is a size check in the script that compares file size to freespace on the DVD, and a format function that calls a batch program that formats the DVD using DLA.

Just checking if anyone can help by just reviewing this and point any mistakes or any code that should change, still kind of a noob at this.

#include <Date.au3>
#Include <Array.au3>
#include <string.au3>
#Include <File.au3>
#include <GUIConstants.au3>

; -------------------------------------------------------------------------------------
; Declaring Variable to be used Globally
; -------------------------------------------------------------------------------------
Global $SourcePath, $DestPath, $MovePath, $LogPath, $DelPath, $Today, $TodayPath, $DelDate, $MoveDate, $FilePath, $Monthly, $TodayPath, $LogAll
Global $ErrorLog, $CopyLog, $MoveLog, $FileCount, $BackupCount, $MoveCount, $MonthDate, $LogFlags, $Date, $MoveLogOpen, $ErrorLogOpen, $ErrorCheck
Global $DeleteLogDate, $DelLog
; -------------------------------------------------------------------------------------

Call("Dates")
Call("Directory")
Call ("Format")
Call ("GetFiles")
Call ("Backup")
Call ("Delete")
Call ("DeleteLog")
Call ("Stats")
Exit

Func Dates()
; --------------------------------------------------------------------------------------
; Modifies the current  date to be used in file and path names
; --------------------------------------------------------------------------------------
    $ShortDate = _DateTimeFormat( _NowCalcDate(),0) ;m/dd/yyyy
    $LongDate = _DateTimeFormat( _NowCalcDate(),1) ;Day Name, Month Name Day, Year
    $LongArray = StringSplit ($LongDate,",",1)
    $DayName = $LongArray[1]
    $ShortArray = StringSplit($ShortDate,"/",1) ;Creates an Array of the date
    $MonthLength = StringLen ($ShortArray[1]) ; Returns the length of the Month
    $DayLength = StringLen ($ShortArray[2]) ; Returns the Length of the Day
    If $MonthLength = 1 Then ; Checks if the Month Length is 1
        $ShortArray[1] = (_StringInsert($ShortArray[1], "0", 0 )) ; If length is 1 then add 0 infront of the month creating MM format       
    EndIf
    If $DayLength = 1 Then ; Checks if the Day length is 1
        $ShortArray[2] = (_StringInsert($ShortArray[2], "0",0)) ; if length is 1 then add 0 infront of the day creating DD format
    EndIf
    $Month = $ShortArray[1] ;Sets Month Variable to the month in the array
    $Day = $ShortArray[2] ; Sets Day Variable to the day in the array
    $Year = $ShortArray[3] ; Sets Year variable to the year in the array
    $DYear = $Year - 1
    $Today = ($Month & "/" & $Day & "/" & $Year)
    $MonthDate = ($Month & "/" & $Year)
    $DelDate = ($Month & "_" & $DYear) ; used in the file path for the folder of recordings that are 1 year old to be deleted
    $MoveDate = ($Month & "_" & $Year)
    $TodayPath = ($Month & "_" & $Day & "_" & $Year)
; --------------------------------------------------------------------------------------
; Retrieves date for 30 days ago to delete logs
; --------------------------------------------------------------------------------------
    $30Day = _DateAdd( 'd',-30, _NowCalcDate()) ; returns the date for 30 days ago
    $30DayArray = StringSplit($30Day,"/",1)
    $30DayLen = stringlen($30DayArray[2])
    If $30DayLen = 1 Then
        $30DayArray[2] = (_StringInsert($30DayArray[2], "0",0))
    EndIf
    $DeleteLogDate = $30DayArray[2] & "_" & $30DayArray[3] & "_" & $30DayArray[1]
; --------------------------------------------------------------------------------------
; Retrieves Tomorrows date to determin if this should be a monthly backup
; --------------------------------------------------------------------------------------
    $Tomorrowdate = _DateAdd( 'd',1, _NowCalcDate()) ; returns the date for tomorrow in yyyy/mm/dd
    $TomorrowArray = StringSplit($Tomorrowdate,"/",1) ; creates an array of tomorrows date
    $TomorrowLen = StringLen($TomorrowArray[2]) ; checks the length of the day in the array
    if $Tomorrowlen = 1 Then ; checks to see if the length is 1 digit
        $TomorrowArray[2] = (_StringInsert($TomorrowArray[2],"0",0)) ; if the day is 1 digit add a 0 infront of the day
    EndIf
    $Tomorrow = $TomorrowArray[3] ; sets variable day tomorrow to the day in the array
; --------------------------------------------------------------------------------------
; Checks to see if it is time for a monthly backup
; --------------------------------------------------------------------------------------
    If $DayName = "Saturday" Then ; Checks if today is Saturday
        If $Tomorrow = 01 Then ; If today is Saturday check to see if tomorrow is the first of the month
            $Monthly = "yes" ; If it is the first of the month set monthly to yes
        ElseIf $Tomorrow = "Monday" Then ; Check if it is Monday
            If $Day = 01 Then ; Check if it is the first of the month
                $Monthly = "yes" ; if it is the first of the month then set Monthly to yes
            Else 
                $Monthly = "no" ; if none of the above match set Monthly to no
            EndIf
        Else 
            $Monthly = "no" ; if day is Saturday and is not the first then set Monthly to no
        EndIf
    Elseif $Tomorrow = 01 Then ; Check to see if tomorrow is the first
        $Monthly = "yes" ; if tomorrow is the first then set monthly to yes
    Else
        $Monthly = "no" ; if it is not the first set Monthly to no
    EndIf
EndFunc
; --------------------------------------------------------------------------------------
; Sets up the file paths
; --------------------------------------------------------------------------------------
Func Directory()
$LogPath = ("c:\Logs\") ; sets the path to the log directory
$SourcePath = ("c:\archive\") ; sets the path to the source directory archive
$DestPath = ("f:\") ; sets the destination path to the DVD
$MovePath = ("c:\archive\" & $MoveDate) ; sets the maint path to the archive and month folder
$DelPath = ("c:\archive\" & $DelDate) ; sets the delete path to the archive and month folder to be deleted year old recordings
$DelLog = ($LogPath & $DeleteLogDate)
$LogAll = $LogPath & $TodayPath & "\ALL_Files.txt" ; sets logall variable to a file path of c:\logs\All_mm/dd/yyyy
$LogFlags = $LogPath & $TodayPath & "\Flags.txt" ; sets LogFlags variable to file path of c:\logs\Flags_mm/dd/yyyy used to show the backup and move flags for the file
$ErrorLog = $LogPath & $TodayPath & "\ERROR.txt" ; sets errorlog variable to a file path of c:\logs\Error_mm/dd/yyyy
$CopyLog = $LogPath & $TodayPath & "\Copy.txt" ; sets copylog variable to a file path of c:\logs\Copy_mm/dd/yyyy
$MoveLog = $LogPath & $TodayPath & "\Move.txt" ; sets movelog variable to a file path of c:\logs\Move_mm/dd/yyyy


EndFunc
; --------------------------------------------------------------------------------------
; Compares the file size to the free space on the DVD
; --------------------------------------------------------------------------------------
Func Size()
    $FileKBSize = filegetsize ($FilePath)
    $FreeSpace = DriveSpaceFree ("F:\")
    $FileMBSize = $FileKBSize / 1048576
    If $FileMBSize > $FreeSpace Then
        Msgbox (0, "Disc Full", "Please insert new disc then press ok.")
        Call ("Format")
    EndIf
EndFunc
; --------------------------------------------------------------------------------------
; Formats the DVD using a batch file
; --------------------------------------------------------------------------------------
Func Format()
Run ("c:\Formatf.bat") ; runs the formatf.bat file located in the c directory
WinWaitActive ("C:\WINDOWS\system32\cmd.exe") ; pauses script until the command prompt window opens from the previous step
WinWaitClose ("C:\WINDOWS\system32\cmd.exe") ; pause the script until that command prompt window closes showing the format is complete
EndFunc
; --------------------------------------------------------------------------------------
; Searches the archive directory and makes a list of the files in the directory and writes to file
; --------------------------------------------------------------------------------------
Func GetFiles()
$LogAllOpen = FileOpen($LogALL,9)
If $LogAllOpen = -1 Then
    MsgBox(0, "Error", "Unable to open file.")
    Exit
EndIf
$FileList = _FileListToArray ($SourcePath, "*.*", 1) ; creates an array of all the files in the archive directory
If (Not IsArray($FileList)) and (@Error=1) Then ; checks the array for errors
    MsgBox (0,"", "No Files\Folders Found.") ; if there is an error send message to the desktop
EndIf

_FileWriteFromArray ($LogAll, $FileList, 1) ; writes the contents of the array to the LogAll file
If @error = 0 Then
    ; msgbox (0,"File List Array","No error")
ElseIf @error = 1 Then
    MsgBox (0, "File List Array","Error opening specified file ")
Elseif @error =  2 Then 
    Msgbox (0, "File List Array","Input is not an Array ")
EndIf
FileClose ($LogallOpen)
EndFunc
; --------------------------------------------------------------------------------------
; Function checks the backup flags and move flags and does appropriate maint.
; --------------------------------------------------------------------------------------
Func Backup()
$LogAllOpen = FileOpen ($LogAll,0) ; Opens the LogAll file in read only mode
$LogFlagsOpen = FileOpen($LogFlags,1) ; Opens the logAll File in write mode to write the files backup and move flags
$CopyLogOpen = FileOpen($CopyLog,1) ; Opens the CopyLog File in write mode to write the files that were backedup
$ErrorLogOpen = FileOpen($ErrorLog,1) ; Opens the ErrorLog File in write mode to write any errors during the backup
$MoveLogOpen = FileOpen($MoveLog,1) ; Opens the MoveLog File in write mode to write the files that were backed up
If $LogAllOpen = -1 Then ; Checks to make sure the file was opened properly
    MsgBox (0, "Error", "Unable to open Daily All Files log in Backup Function") ; if problem opening file display message
    Exit ; Then when OK is click exit script
EndIf
$FileCount = 0 ; Sets the FileCount to 0 to track how many files were found for the backup
$BackupCount = 0 ; Sets the BackupCount to 0 to track how many files were backed up
$MoveCount = 0 ; set the MoveCount to 0 to track how many file were moved
$ErrorCheck = "no" ; sets errorcheck to no to track if there were any errors in the backup function
If $Monthly = "yes" Then ; Checks to see if this is a monthly backup
    $Date = $MonthDate ; if so set Date to mm/yyyy
    $MoveFile = "yes" ; seeing it is a monthly backup lets set the move flag to yes
Else
    $Date = $Today ; if not a monthly set date to mm/dd/yyyy
    $MoveFile = "no"
EndIf
While 1 ; Starts a loop to read each line individually
    $LogAllRead = FileReadLine ($LogAllOpen) ; Reads line from the LogAll file
    If @error = -1 Then ExitLoop ; Checks if it is EOF if so exit loop
    $FilePath = ($SourcePath & $LogAllRead)
    $FileDateArray = FileGetTime ($FilePath, 1,0) ; creates an array of the files created date stamp in YYYYMMDDHHMMSS format
    If Not @error Then ; Checks to make sure that the file date is in an array
        $FileYear = $FileDateArray[0] ; sets FileYear to the year in the array
        $FileMonth = $FileDateArray[1] ; sets FileMonth to the month in the array
        $FileDay = $FileDateArray[2] ; sets FileDay to the day in the array
        $FileDateDay = $FileMonth & "/" & $FileDay & "/" & $FileYear ; sets variable FileDateDay to the files created date stamp in mm/dd/yyyy format daily backup
        $FileDateMonth = $FileMonth & "/" & $FileYear ; sets variable FileDate to the files created date stamp in mm/dd/yyyy format form monthly backup
    EndIf
    If $Monthly = "yes" Then ; check to see if monthly is yes
        $FileDate = $FileDateMonth ; if monthly is yes then set the date format to mm/yyyy
    Else 
        $FileDate = $FileDateDay ; if monthly is not yes then set date format to mm/dd/yyyy
    Endif
    If $FileDate = $Date Then ; Checks to see if the FileDate Matches the current date
        $BackupFile = "yes" ; if the dates match then set to yes
    Else
        $BackupFile = "no" ; else set to no
    EndIf
    $Flags = ($FilePath & "; " & $FileDate & "; Backup File = " & $BackupFile & "; Move File = " & $MoveFile) ; set flags variable to the file path; file date; backup; move flags
    FileWriteLine ($LogFlagsOpen,$Flags) ; writes the flags variable to log file to keep track of what was suppose to be backed up
    If $BackupFile = "yes" Then ; check to see if the backup flag is yes
        ;Call ("Size") ; if yes then check to make sure there is enough space on the DVD for the file by calling the Size Function
        $Backup = FileCopy ($FilePath, $DestPath, 9) ; Copies the file to the DVD
        If $Backup = 1 Then ; checks to see if there were any errors copying the file
            FileWriteLine($CopyLogOpen, $FilePath & " was copied to " & $DestPath) ; if no errors then write the file path to the Copied Log for that day
            $BackupCount = $BackupCount + 1 ; add 1 to the Backuped File count
        Else
            FileWriteLine($ErrorLogOpen, $FilePath & " Failed to Copy to DVD") ; if there was an error write the file path to the Error Log for that day
            $Errorcheck = "yes"
        EndIf
        If $MoveFile = "yes" Then ; checks to see if the movefile flag is set to yes
        Call ("Move") ; if set to yes call the Move function
        EndIf
        $FileCount = $FileCount + 1 ; add 1 to the file count to track how many files should have been copied today
    EndIf
Wend
FileClose ($LogAllOpen) ; closes the LogAll file
FileClose($LogFlagsOpen) ; closes the LogFlags file
FileClose($CopyLogOpen) ; Closes the CopyLog File
FileClose($ErrorLogOpen) ; Closes the ErrorLog File
FileClose ($MoveLogOpen) ; Closes the MoveLog File
EndFunc
; --------------------------------------------------------------------------------------
; Moves the file to the months directory
; --------------------------------------------------------------------------------------
Func Move()
    $FileMove = FileMove($FilePath, $MovePath & "\",9) ; moves the file to the folder for the month
    If $FileMove = 1 then ; checks to see if the file moved properly
        $MoveCount = $MoveCount + 1 ; if no errors then add 1 to the movecount
        FileWriteLine($MoveLogOpen, $FilePath & " was moved to " & $MovePath) ; then write the file path and was moved to and the destination path to the move log
    Else
        FileWriteLine($ErrorLogOpen, $FilePath & " was not moved to " & $MovePath) ; if there was an error then write the file path and then was not moved to the destination path 
        $ErrorCheck = "yes"
    EndIf
EndFunc
; --------------------------------------------------------------------------------------
; Deletes the folder of files that are 1 year old
; --------------------------------------------------------------------------------------
Func Delete()
    If $Monthly = "yes" Then
        DirRemove ($DelPath, 1)
    EndIf
EndFunc
; --------------------------------------------------------------------------------------
; Deletes the logs that are 30 days old
; --------------------------------------------------------------------------------------
Func DeleteLog()
    DirRemove($DelLog,1)
Endfunc
; --------------------------------------------------------------------------------------
; Displays the statistics of the backup for that day
; --------------------------------------------------------------------------------------
Func Stats()
If $Monthly = "yes" then
    $BackupType = "Monthly"
Else
    $BackupType = "Daily"
EndIf
$oRP = ObjCreate("RICHTEXT.RichtextCtrl.1")
Opt("GUIOnEventMode", 1)  ; Change to OnEvent mode 
$mainwindow = GUICreate("Backup Statistics", 300, 450)
GUISetOnEvent($GUI_EVENT_CLOSE, "CLOSEClicked")
GUICtrlCreateLabel("Daily Backup:", 100, 10)
GUICtrlCreateLabel("Yesterday's File count was:", 40, 30)
GUICtrlCreateLabel("Backed up Successfully:", 50, 50)
GUICtrlCreateLabel("Moved Count:", 100, 90)
GUICtrlCreateLabel($BackupType, 175, 10)
GUICtrlCreateLabel($FileCount, 175, 30)
GUICtrlCreateLabel($BackupCount, 175, 50)
GUICtrlCreateLabel($MoveCount, 175, 90)
GUICtrlCreateLabel("Errors during backup", 90,130)
GUICtrlCreateLabel("if any errors click on window and use arrow keys to scroll", 10,150)
$GUIActiveX = GUICtrlCreateObj( $oRP, 20, 20 , 100 , 100 )
GUICtrlSetPos($GUIActiveX,10,170,275,225)
$okbutton = GUICtrlCreateButton("OK", 115, 410, 60)
GUICtrlSetOnEvent($okbutton, "OKButton")
GUISetState(@SW_SHOW)

With $oRP; Object tag pool
.OLEDrag()
.Font = 'Arial'
.FileName = $ErrorLog
;.BackColor = 0xff00
EndWith

While 1
  Sleep(1000)  ; Idle around
WEnd
EndFunc
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Func OpenError()
    run ("Notepad.exe")
    WinWaitActive("Untitled - Notepad")
    WinActivate("Untitled - Notepad")
    send("{CTRLDOWN}")
    send ("o")
    Send ("{CTRLUP}")
    WinWaitActive("Open")
    WinActivate("Open")
    Send($ErrorLog)
    Send ("{ENTER}")
EndFunc
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Func OKButton()
    Exit
EndFunc

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Func CLOSEClicked()
    Exit
EndFunc

Thanks in advance any opinions or comments are greatly appreciated

Edited by mnchartier
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...