AutoHotkey Community

It is currently May 26th, 2012, 7:15 pm

All times are UTC [ DST ]




Post new topic Reply to topic  [ 2 posts ] 
Author Message
PostPosted: April 4th, 2009, 6:32 pm 
Offline

Joined: April 4th, 2009, 5:10 pm
Posts: 5
The objective is to provide automated daily back that can manually started, run unattended and then shut the computer down. The user would click a short cut at the end of the day and walk away. A rotating back up would maintain three versions, each on a different hard disk.

Appended are three ahk scripts achieving this objective. Script #0 is complete in itself. Scripts #1 and # 2 work together as a team.

The scripts select the next drive to receive a backup and check that it is turned on and scan for new devices if not. Next it will select the type of back up software to call, either file copy or a disk image, using dedicated backup software. The script makes an image backup on steps one and nine in a 16 step cycle, otherwise it calls for a file back up. If an image backup is called for, the script will delete old backups to make room for new images if required. After the back up the script will (thinly) log results shut the computer down.

Script #0 runs on the same instance of Windows that it was launched in using some form of volume shadow copy. This is normally quite acceptable but may not capture files and changes made if the user continues to work after shadow copy is called. If required, Scripts #1 and #2 can be used to avoid this situation by having script 1 do the most of the setup work then boot to a second instance of Windows (a parallel installation) which carries out the imaging process as a GPO (gpedit.msc) startup script. File locking issues are avoided since the main instance of Windows is asleep during the backup and no user files are open. The second instance could also do the file copy backup but since this takes 3 minutes or less, and may be done a few times in one day by a paranoid user (me), it does not seem to make sense to reboot.

These scripts are running on Windows XP computers and are spcialized for GoodSync, Image for Windows and BootIT NG commandline utilities. You can easily modify them to work with other software packages: there are a number of free and very reliable utilites that could be used instead, some are mentioned in the scripts.

The ahk code is uncomplicated and workaday, demonstrating no special ahk insights. Strings are usually set in the old syntax "strVal=Some Text". More use could have been made of the, in my view improved, strVal := "Some Text". Working with AutoHotKey is a joy compared to the other Windows Scripting options I have tried.

Scripts #1 & #2 are in the next post with the same title.

Code:
;------------------------------------------------------------------------------------------
; Script #0
;
; Autohotkey script to create either a daily rotating incremental back up and rotating
; disk image file every 8 days. Both types of backup are done without leaving in the
; instance of Windows that launches the script.
;
; Backups are done using some form of shadow copy depending on the software package
; called by the script. Files added/changed after shadow copy starts may not be backed up.
; This is not usually serious but can be avoided by using Scripts #1 and #2.  These
; boot a second instance of Windows (a parallel installation) and image from there.
;
; Note: Change the extension on this file from .txt to .ahk before running it.  It was
;       posted as .txt for security reasons.
;
; Three versions are maintained for each type of back up, one on each of three
; eSATA/USB drives but you could also use mapped folders on the same drive or
; mapped network folders. 
;
; The script will check to see if the back up drives are turned on before backing up. If it
; is making an image file, it will delete the oldest image files if required. You can
; set a quota on the space allowed for image files.
;
; Every time you back up it, Script one advances the backup count in a 16 step cycle.  On steps
; 1 and 9 it boots to a second instance of windows where the image file is created.
; On the other counts it does a file sync back up on instance #1 of windows. Of course
; you can modify the script to to alter these arangements as required.
;
; You Need:
;
;  Autohotkey, indispensible and free from www.autohotkey.com.
;     See See http://www.autohotkey.com/docs/commands.htm for a list of commands.
;
;  Imaging software: I recommend Image for Windows www.terabyteunlimited.com.  Not free but very reliable and
;     inexpensive.  Aka IFW.  You can down load a console version, IFWC.exe, that is ideal for scripting. If
;     you buy BING you may not need imaging software.  It can create images all by itself and can be batched.
;     Use version 1.99 of TBIview (a Windows Program) to extract files one at a time, from the BING created image.
;
;  File backup software: I like GoodSync, www.goodsync.com. There is a console version, gsync, that is
;     ideal for scripting. There are many other free options including xxcopy from Pixie labs,
;     http://www.xxcopy.com/index.htm which I believe is an excellent choice.
;
;  Any text editor
;------------------------------------------------------------------------------------------

#NoEnv               ; We will not be using Windows environment variables

MsgBox,4,,Back Up?   ; Give user a chance to exit gracefully

ifMsgBox No
{
   exit              ; return to windows
}

;------------------------------------------------------------------------------------------
; This script uses Windows file names to keep track of the backup count.
;
; Set the global variables to provide locations for the back up counter records (files),
; and specify a name for the main backup counter file.
;
; Do some measuring before specifying Min_GB  and QuotaGB.  Min_GB  is the number of
; GigaBytes required for one complete image backup which may consist of several separate
; image files. In my case I need room for two .TBI files totalling 65 GB so I set Min_GB
; to 75 GB allowing room to grow.  QuotaGB is the maximum number of Gigabytes I am willing
; to allocate to image files.  I want room for two separate image backups on each backup
; disk, that way I have two versions, a few weeks apart, on hand.  I set QuotaGB 
; to 166 GB.  This will erase, what would have been a third version, before re-imaging
; the source drive.
;------------------------------------------------------------------------------------------

;--- Define Global vars
CurrFlagDir = D:\Documents and Settings\xx\Desktop\Shutdown_BU\BU Tools       ; Location of status files for current back up
PrevFlagDir = D:\Documents and Settings\xx\Desktop\Shutdown_BU\BU Tools\Prev  ; location of status files for previous back up
BackFile  = LastBack_1.log                                                    ; Initial value of main step counter file
Min_GB    := 75                                                               ; Minimim disk space required for one image back up file set (GB)
QuotaGB   := 166                                                              ; Maximum space to allow for all image file sets on one disk (GB)

;--- Find the next step count in the backup cycle
k := TrackStatus()   ; Subroutine to manage counters tracking position in where back up cycle and
                     ; what type of backup to do. k is the step number in 16 day cycle

;--- Do a file backup, or create an image backup, depending on the step count
If(k=1 or k=9)
   MakeImage()      ; Do a complete back up using disk imaging software
else
   FileBackup()     ; Do a file backup

ShutDown()          ; Power down

return              ; End of main routine.  Subroutines below.
 

;##########################################################################################
; Function to make sure back up drives are turned on/available or quit
;##########################################################################################

CheckDrive(D)
{
   Global PrevFlagDir
   Global CurrFlagDir
   
   ;--- Make sure back up drive is turned on/available
   DrvUp := 0          ; define a variable for one of the drives U:\, V:\, or W:\
   
   ifExist,%D%:\       ; D is the argument passed to CheckDrive()
   {
      DrvUp := 1
   }
   
   if NOT DrvUp
   {
      ;-------------------------------------------------------------------
      ; We need to turn one of the drives on and get the device manager
      ; to install them. (This BIOS on this computer is in IDE mode
      ; not AHCI or RAID)
      ;-------------------------------------------------------------------
     
      MsgBox Turn Backup Drive %D%: On     
     
      ;--------------------------------------------------------------------
      ; Rescan for new devices now that the BU drives have been started
      ; Get the free devcon x32 and x64 at
      ; http://support.microsoft.com/default.aspx?scid=kb;en-us;Q311272
      ;--------------------------------------------------------------------
     
   
      loop
      {
         RunWait devcon rescan   
         
         Sleep 3000          ; Wait three seconds for device to materialize after scan

         ifExist,%D%:\       ; D is the argument passed to CheckDrive()
            DrvUp := 1
         else
            DrvUp := 0
         
         if DrvUp
            scanMsg = Back up drive %D% is ready: Backup now?
         else
            scanMsg = *** Drive %D% NOT found! Start backup anyway? ***
         
         MsgBox,3,,%scanMsg%`nClick Yes to start backup, No to rescan for drives, Cancel to return to Windows
   
         ifMsgBox No
         {
            RunWait devcon rescan
         }
           
         ifMsgBox Yes
         {
            break
         }
           
         ifMsgBox Cancel
         {
            ;--- Undo previous save
            FileDelete, %CurrFlagDir%\Last*.*                      ; clean up destination before copy 
            FileCopy, %PrevFlagDir%\Last*.*, %CurrFlagDir%\*.*
            exit   ; return to Windows
         }
      }
   }   
   return
}

;#######################################################################################################
; Function to create an image (Complete) back up
;#######################################################################################################

MakeImage()
{
   ;---------------------------------------------------------------------------------------------------
   ; Create a disk image on one of three rotating locations (i.e. keep at least 3 most recent versions)
   ;---------------------------------------------------------------------------------------------------
   
   ;--- Update imag counter
   
   Global CurrFlagDir   

   SetWorkingDir, %CurrFlagDir%   
   
   k := 99

   ImagList := "UVW"              ; List of destination drive letters
   
   Loop, Parse, ImagList
   {
      ifExist, LastImag_%A_LoopField%.log
      {
         k := A_Index
         break
      }
   }
   
   NextFile = LastImag_U.log   ; Initialize backup status flag

   if (k=99)
   {
      ; no previous record of back up found
      k = 1
   }
   else
   {
      ; previous back up found
     
      List1 = LastImag_U.log     ; create an array of counter names
      List2 = LastImag_V.log
      List3 = LastImag_W.log

      k := k+1                   ; advance counter 

      if(k=4)                    ; wrap counter
      {
         k:=1
      }

      NextFile := List%k%        ; name the next file
   }

   FileDelete, LastImag*.*       ; clean up previous back up records
   FileAppend,,%Nextfile%        ; create new file to record bu that is about to happen

   ;--- Create dated names for the image files
   fn1 = BU %A_YYYY%-%A_MM%-%A_DD% WinXP 80GB_IDE_Mode_ahk
   fn2 = BU %A_YYYY%-%A_MM%-%A_DD% DATA  80GB_IDE_Mode_ahk

   ;--- Select destination drive
   Drv := SubStr(ImagList,k,1)   ; Destination drive letter
   CheckDrive(Drv)               ; Make sure BU Drive is turned turned on...or exit.
     
   ;--- Make room on destination drive by deleteing oldest backup(s), if required
   FilePattern = %Drv%:\BU*.tbi  ; Don't forget the dot and extension
   
   ok := MakeRoom(FilePattern,NextFile)
   
   if (NOT ok)
   {
      ;--- Insufficient disk space to back up
      msg = *** BACKUP CANCELLED ***`nInsufficient space for backup on drive %Drv%:
      FileAppend, %msg%, %Nextfile%       ; log failure of back up
     
      MsgBox, 4, ,%msg%`nShutdown?, 90    ; give user 90 seconds to cancel shutdown
     
      IfMsgBox Timeout
         ShutDown()
         
      ifMsgBox Yes
         ShutDown()
         
      ifMsgBox No
         return
   }

   ;--- Ok lets back  up: Call your favorite imaging program here: I use "Image for Windows" console version

   idir := "C:\Program Files\TeraByte Unlimited\Image for Windows\V2\"           ; Starting directory for IFWC.EXE
   
   RunWait, imagewc.exe /b /d:?C:  /f:"%Drv%:\%fn1%" /uy /v /vb, %idir%          ; Back up windows C: drive
   FileAppend,Resulting Errorlevel for %fn1% = %ErrorLevel%`n, %Nextfile%        ; Record exit code for imaging program

   RunWait, imagewc.exe /b /d:?D: /f:"%Drv%:\%fn2%" /uy /v /vb, %idir%           ; Back up DATA located on drive letter D:
   FileAppend,`nResulting errorlevel for %fn2% = %ErrorLevel%`n, %Nextfile%      ; Record exit code for imaging program program
   
   ;------------------------------------------------------------------------------------------------------------------------------------------------
   ; RunWait, imagewc.exe /b /d:w1@0x490 /f:"%Drv%:\%fn2%" /uy /v /vb, %idir%    ; Alternate syntax using ID number, works when DATA partition is hidden
   ;                                                                             ; ID numbers can be volatile: use SeqVolID=1 in IFW.INI to stabilize
   ;------------------------------------------------------------------------------------------------------------------------------------------------                                                     
   ; RunWait, imagew.exe /b /d:?F: /f:"W:\test" /uy, %idir%                      ; test alt syntax by imaging a USB stick with drive letter F:                           
   ; RunWait, imagew.exe /b /d:w0@0xEF  /f:"%Drv%:\%fn1%" /uy /v /vb, %idir%     ; tiny partition on Dosk 0 for testing
   ; Commands saved with IFWC.EXE F8 Key:
   ;   "C:\Program Files\TeraByte Unlimited\Image for Windows\V2\imagewc.exe" /b /d:w0       /f:"U:\aaa" /v /vb
   ;   "C:\Program Files\TeraByte Unlimited\Image for Windows\V2\imagewc.exe" /b /d:w1@0x490 /f:"U:\aaa" /v /vb
   ;------------------------------------------------------------------------------------------------------------------------------------------------
   
   return
}

;###############################################################################################################
; Function to synchronize main and backup disks (File Back Up)
;###############################################################################################################

FileBackup()
{
   ;-------------------------------------------------------------------------------------------------------
   ; Create a "file type" back up on one of three rotating locations (i.e. keep three most recent versions)
   ; This script causes an incremental back up that takes about 10 minutes a day and copies the data files
   ; to one of three destination drives where they can be browsed in Windows Explorer
   ;-------------------------------------------------------------------------------------------------------

   Global CurrFlagDir
   
   SetWorkingDir, %CurrFlagDir%

   k := 99

   SyncList := "UVW"

   Loop, Parse, SyncList
   {
      ifExist, LastSync_%A_LoopField%.log
      {
         k := A_Index
         break
      }
   }

   NextFile = LastSync_U.log     ; initialize status counter
   
   if (k=99)
   {
      ;--- no previous record found
      k := 1
   }
   else
   {
      ;--- found previous status counter

      List1 = LastSync_U.log  ; create an array of counter names
      List2 = LastSync_V.log
      List3 = LastSync_W.log

      k := k+1               ; advance counter 

      if(k=4)                ; wrap counter
      {
         k:=1
      }

      NextFile := List%k%    ; name the next file
   }

   FileDelete, LastSync*.*   ; clean up
   FileAppend,,%Nextfile%    ; create new file to record bu that is about to happen

   ;-------------------------------------------------------------------------------------------------
   ; Call your favourite file sync program: I use GoodSync but the free xxcopy from Pixie Labs works
   ;-------------------------------------------------------------------------------------------------

   Job := "XXX"        ; Name of GoodSync backup job
   
   if(k=1)
   {
      Job := "Bu2U"    ; Back up to U:\
   }
   
   if(k=2)
   {
      Job := "Bu2V"    ; Back up to V:\
   }
   
   if(k=3)
   {
      Job := "Bu2W"    ; Back up to W:\
   }
   
   ;--- Select destination drive
   D := SubStr(SyncList,k,1)     ; Destination drive letter
     
   ;--- Make sure drive is turned on ... or quit
   CheckDrive(D)
   
   RunWait, gsync.exe /exit sync %Job%, C:\Program Files\Siber Systems\GoodSync

   FileAppend,Resulting errorlevel for sync %Job% = %ErrorLevel%`n, %Nextfile%  ; Record exit code for sync program
   
   return
}

;#####################################################################################################
; Subroutine to Shut down the computer down
;#####################################################################################################

ShutDown()
{
   Global BackFile

   ;--- Log completion time
   buMsg = Completed Back up at %A_YYYY%-%A_MM%-%A_DD% %A_Hour%:%A_Min%:%A_Sec% `n

   FileAppend, %buMsg%, %Backfile% ; Log that is about to happen

   MsgBox, 4, , Shutdown?, 100     ; Give user 100 seconds to abort. Proceed if nobody is around

   Ans := 1                        ; var to code user response

   IfMsgBox Timeout                ; No one at the keyboard
      Ans := 1

   ifMsgBox Yes                    ; Shutdown was requested
      Ans := 1

   IfMsgBox No                     ; Stay running was requested
      Ans := 0

   ;--- Shutdown and power off
   
   If (Ans = 1)
   {     
      ;--- Shutdown
      ;--- An option: Run, BootNow.exe /Shutdown, c:\windows\system32
     
      Run, tsshutdn.exe 5 /POWERDOWN /DELAY:5, c:\windows\system32   
   }

   ;--------------------------------------------------------------------------------------
   ; Shutdown options: TSSHUTDN.EXE, DEVCON.EXE, BOOTNOW.EXE
   ; BootNow is very reliable and free from Terrabyte Unlimited. 
   ;    You need to create a BOOTNOW.INI. See the BOOTNOW readme. See MakeBootNowINI()
   ;    in Script #1. Use diskmgmt.msc to find the drive number where BING is stored
   ; TSSHUTDN.EXE is part of Windows XP Pro, Press Escape to abort
   ;--------------------------------------------------------------------------------------

   return
}

;#####################################################################################################
; Subroutine to manage and update status flag files
;#####################################################################################################

TrackStatus()
{
   Global PrevFlagDir
   Global CurrFlagDir
   Global BackFile
   
   ;--- Define location of status records
   SetWorkingDir, %CurrFlagDir%   

   ;--- Record previous state
   FileDelete, %PrevFlagDir%\Last*.*                       ; clean up destination before copy 
   FileCopy, %CurrFlagDir%\Last*.*, %PrevFlagDir%\*.*      ; record prev BU status in Prev Folder
   
   k := 99                            ; Variable to hold current step count

   BuIDList := "1234567890abcdef"     ; List of all possible backup counter values

   Loop, Parse, BuIDLisT              ; Search for filename identifying the previous count
   {
      ifExist, LastBack_%A_LoopField%.log
      {
         ;-- Found a file called eg "LastBack_6.log" or "LastBack_f.log")
         k := A_Index     ; return present position in the BuIDList
         break
      }
   }

   BackFile = LastBack_1.log  ; Initialize step counter

   if (k=99)
   {
      ;--- No previous record of back up
      k := 1                   ; start at the top of the cycle
   }
   else
   {
      ;--- Record of previous backup found
      k := k+1               ; advance counter 
      if(k=17)               ; wrap counter
         k:=1

      flag := SubStr(BuIDList,k,1)      ; Display value for status flag
      BackFile = LastBack_%flag%.log    ; filename the next backup counter (old ahk syntax used)
   }

   buMsg = Starting Back up initiated on %A_YYYY%-%A_MM%-%A_DD% %A_Hour%:%A_Min%:%A_Sec% `n

   FileDelete, LastBack*.*              ; clean up previous state flags
   FileAppend, %buMsg%, %BackFile%      ; create new file to record bu that is about to happen
   
   return k
}

;######################################################################################################
; Subroutines to manage image backups by deleting old backups, if required
;######################################################################################################

GetGB(FilePattern)
{
   ;--- Calculate the sum of file sizes for all files
   ;--- in a folder matching the FilePattern Var
   ;--- Calculate the sum in bytes and divide by 10**9
   
   Sum := 0
   
   Loop, %FilePattern%, , 0
       Sum += %A_LoopFileSize%
       
   return Sum/1000000000  ; sum of file sizes in GiB
}

MakeRoom(FilePattern,NextFile)
{
   Global QuotaGB 
   Global Min_GB
   
   Result := 0                                             ; Not ok to back up
   
   loop
   {
      FreeGB := 0                                          ; Var to hold space available on disk
     
      Drv := Substr(Filepattern,1,3)                       ; Destination drive letter eg W:\
     
      DriveSpaceFree, FreeGB, %Drv%                        ; get space available on disk
     
      FreeGB /= 1000                                       ; Change MB to GB
     
      CurrSize := GetGB(FilePattern)                       ; Total size of existing back up files 

      if ((CurrSize > QuotaGB) OR (FreeGB < Min_GB ))
      {
         ;--- Delete the oldest backup file

         FileList = ;                                                            ; Make a varaiable to hold list of back up files

         Loop, %FilePattern%, 1
             FileList = %FileList%%A_LoopFileTimeCreated%`t%A_LoopFileName%`n    ; Save list of file names and creation dates to a string

         Sort, FileList                                                          ; Sort by date, Oldest first

         if (StrLen(FileList) < 1)
         {
            ;--- no back ups left to delete!
            Result := 0
            break
         }

         FileName =                                                             ; Var to hold name of file to be deleted

         Loop, parse, FileList, `n                                              ; Get first file name on list
         {
             StringSplit, FileItem, A_LoopField, %A_Tab%                        ; Split into two parts at the tab char.
             FileName := FileItem2                                              ; Save the name
             break
         }   

         StringTrimRight, Path, FilePattern, 7                                  ; Path to target file

         Target = %Path%%FileName%                                              ; Pattern to delete

         FileAppend, MakeRoom() deleted image file "%Target%"`n,%NextFile%      ; log delete

         FileDelete, %Target%                                                   ; Ok! One image file gone
      }
      else
      {
         Result := 1
         break
      }
   }
   return Result
}


Report this post
Top
 Profile  
Reply with quote  
 Post subject:
PostPosted: June 1st, 2009, 5:51 am 
Offline
User avatar

Joined: August 30th, 2005, 8:43 pm
Posts: 8666
Location: Salem, MA
Here is the remainder of the code (copied from the other topic for clarity)
AL_S wrote:
Here are scripts 1 & #2 refered to in the previous post with the same name.

Code:
;---------------------------------------------------------------------------------------------------------------------------
; Script #1
;
; Note: Change the extension on this file from .txt to .ahk before running it.  It was posted
;       as .txt for security reasons.
;
; Install a shortcut to this script on your desk top. At the end of the day double click and
; computer will either make a file copy backup boot or an image backup and then shut down.
; The script will erase old image files to make room for new backup if required.  You can set a
; quota on the amount of space allowed for image files. Three versions of each type of backup
; are kept in a rotating back up on disks U, V & W which can be three physical disks or
; three mapped folders on the same backup disk. 
;
; Every time you back up it, Script one advances the backup count in a 16 step cycle.  On steps
; 1 and 9 it boots to a second instance of windows where the image file is created.
; On the other counts it does a file sync back up on instance #1 of windows. Of course
; you can modify the script to to alter these arangements as required.
;
; This script requires two instances of Windows on the same computer.  File backups are done
; in the first instance of Windows using volume shadow copy.  Images are made in the second
; instance of Windows to avoid file locking issues and ensure that the backup is complete and
; up to date. On my computer file back up takes 3 minutes.  Imaging takes 50 minutes. So I
; use this script as a daily backup routine.
;
; This script uses the free BootNow.exe utility from Terabyte International to boot to
; another partition that auto-runs an Image for Windows script to image all partitions. See
; Script #2 for additional details.
;
; You Need:
;  Autohotkey, free from www.autohotkey.com. See See http://www.autohotkey.com/docs/commands.htm
;     for a list of commands
;  BootIt NG,  from www.terabyteunlimited.com.  Not free but very reliable and inexpensive.  Aka BING.
;  BootNow.exe free from Terrabye Unlimited.
;  Imaging software: I recommend Image for Windows www.terabyteunlimited.com.  Not free but very reliable and
;     inexpensive.  Aka IFW.  You can down load a console version, IFWC.exe, that is ideal for scripting. If
;     you buy BING you may not need imaging software.  It can create images all by itself and can be batched.
;     Use version 1.99 of TBIview (a Windows Program) to extract files one at a time, from the BING created image.
;  File backup software: I like GoodSync, www.goodsync.com. There is a console version, gsync, that is
;     ideal for scripting. There are many other free options such as xxcopy from Pixie labs,
;     http://www.xxcopy.com/index.htm is an ecellent choice.
;  Any text editor
;
; One Way to create a second instance of Windows:
;  Boot the recovery disk that came with your partitioning software.  I greatly prefer BING to Partition Magic.
;  Create a small (8 - 30 MB) partition and install a boot manager.  I greatly prefer BING to BootMagic.
;  Use the partitioning software to create a new partition of 16 GB or larger. Restore or copy a previous
;  image of Windows to the new partition, or just reinstall from your Windows CD.  You might have to resize
;  the existing partitions before installing a second instance of Windows.  Take the usual precautions when
;  running the second instance of windows: I turn off System restore and disable the indexing service.
;
;  Whenever I install Windows, I make an image of the installation after all updates are applied and before
;  any application software is installed. This image is used whenever another instance of Windows is required
;  on that computer.
;---------------------------------------------------------------------------------------------------------------------------

#NoEnv               ; We will not be using Windows environment variables

MsgBox,4,,Back Up?   ; Give user a chance to exit gracefully

ifMsgBox No
{
   exit              ; return to windows
}

;------------------------------------------------------------------------------------------
; This script uses Windows file names to keep track of the backup count.
;
; Set the global variables to provide locations for the back up counter records (files),
; and specify a name for the main backup counter file.
;
; Do some measuring before specifying Min_GB  and QuotaGB  .  Min_GB  is the number of
; GigaBytes required for one complete image backup which may consist of several separate
; image files. In my case I need room for two .TBI files totalling 65 GB so I set Min_GB
; to 75 GB allowing room to grow.  QuotaGB   is the maximum number of Gigabytes I am willing
; to allocate to image files.  I want room for two separate image backups on each backup
; disk, that way I have two versions, a few weeks apart, on hand.  I set QuotaGB 
; to 166 GB.  This will erase, what would have been a third version, before re-imaging
; the source drive.
;------------------------------------------------------------------------------------------

;--- Define Global vars
CurrFlagDir = D:\Documents and Settings\Al\Desktop\Shutdown_BU\BU Tools       ; Location of status files for current back up
PrevFlagDir = D:\Documents and Settings\Al\Desktop\Shutdown_BU\BU Tools\Prev  ; location of status files for previous back up
BackFile  = LastBack_1.log                                                    ; Initial value of main step counter file
Min_GB    := 75                                                               ; Minimim disk space required for one image back up file set (GB)
QuotaGB   := 166                                                              ; Maximum space to allow for all image file sets on one disk (GB)
BingName  := "BING"                                                           ; Name of partition where you installed BootIt NG

;--- Find the next step count in the backup cycle
k := TrackStatus()   ; Subroutine to manage counters tracking position in where back up cycle and
                     ; what type of backup to do. k is the step number in 16 day cycle

;--- Do a file backup, or create an image backup, depending on the step count
If(k=1 or k=9)
   MakeImage()      ; Do a complete back up using disk imaging software
else
   FileBackup()     ; Do a file backup

ShutDown()          ; Power down

return              ; End of main routine.  Subroutines below.
 

;##########################################################################################
; Function to make sure back up drives are turned on/available or quit
;##########################################################################################

CheckDrive(D)
{
   Global PrevFlagDir
   Global CurrFlagDir
   
   ;--- Make sure back up drive is turned on/available
   DrvUp := 0          ; define a variable for one of the drives U:\, V:\, or W:\
   
   ifExist,%D%:\       ; D is the argument passed to CheckDrive()
   {
      DrvUp := 1
   }
   
   if NOT DrvUp
   {
      ;-------------------------------------------------------------------
      ; We need to turn one of the drives on and get the device manager
      ; to install them. (This BIOS on this computer is in IDE mode
      ; not AHCI or RAID)
      ;-------------------------------------------------------------------
     
      MsgBox Turn Backup Drive %D%: On     
     
      ;--------------------------------------------------------------------
      ; Rescan for new devices now that the BU drives have been started
      ; Get the free devcon x32 and x64 at
      ; http://support.microsoft.com/default.aspx?scid=kb;en-us;Q311272
      ;--------------------------------------------------------------------
     
   
      loop
      {
         RunWait devcon rescan   
         
         Sleep 3000          ; Wait three seconds for device to materialize after scan

         ifExist,%D%:\       ; D is the argument passed to CheckDrive()
            DrvUp := 1
         else
            DrvUp := 0
         
         if DrvUp
            scanMsg = Back up drive %D% is ready: Backup now?
         else
            scanMsg = *** Drive %D% NOT found! Start backup anyway? ***
         
         MsgBox,3,,%scanMsg%`nClick Yes to start backup, No to rescan for drives, Cancel to return to Windows
   
         ifMsgBox No
         {
            RunWait devcon rescan
         }
           
         ifMsgBox Yes
         {
            break
         }
           
         ifMsgBox Cancel
         {
            ;--- Undo previous save
            FileDelete, %CurrFlagDir%\Last*.*                      ; clean up destination before copy 
            FileCopy, %PrevFlagDir%\Last*.*, %CurrFlagDir%\*.*
            exit   ; return to Windows
         }
      }
   }   
   return
}

;#######################################################################################################
; Function to create an image (Complete) back up
;#######################################################################################################

MakeImage()
{
   ;---------------------------------------------------------------------------------------------------
   ; Create a disk image on one of three rotating locations (i.e. keep at least 3 most recent versions)
   ;---------------------------------------------------------------------------------------------------
   
   ;--- Update imag counter
   
   Global CurrFlagDir   

   SetWorkingDir, %CurrFlagDir%   
   
   k := 99

   ImagList := "UVW"              ; List of destination drive letters
   
   Loop, Parse, ImagList
   {
      ifExist, LastImag_%A_LoopField%.log
      {
         k := A_Index
         break
      }
   }
   
   NextFile = LastImag_U.log   ; Initialize backup status flag

   if (k=99)
   {
      ; no previous record of back up found
      k = 1
   }
   else
   {
      ; previous back up found
     
      List1 = LastImag_U.log     ; create an array of counter names
      List2 = LastImag_V.log
      List3 = LastImag_W.log

      k := k+1                   ; advance counter 

      if(k=4)                    ; wrap counter
      {
         k:=1
      }

      NextFile := List%k%        ; name the next file
   }

   FileDelete, LastImag*.*       ; clean up previous back up records
   FileAppend,,%Nextfile%        ; create new file to record bu that is about to happen

   ;--- Create dated names for the image files
   fn1 = BU %A_YYYY%-%A_MM%-%A_DD% WinXP 80GB_IDE_Mode_ahk
   fn2 = BU %A_YYYY%-%A_MM%-%A_DD% DATA  80GB_IDE_Mode_ahk

   ;--- Select destination drive
   Drv := SubStr(ImagList,k,1)   ; Destination drive letter
   CheckDrive(Drv)               ; Make sure BU Drive is turned turned on...or exit.
     
   ;--- Make room on destination drive by deleteing oldest backup(s), if required
   FilePattern = %Drv%:\BU*.tbi  ; Don't forget the dot and extension
   
   ok := MakeRoom(FilePattern,NextFile)
   
   if (NOT ok)
   {
      ;--- Insufficient disk space to back up
      msg = *** BACKUP CANCELLED ***`nInsufficient space for backup on drive %Drv%:
      FileAppend, %msg%, %Nextfile%       ; log failure of back up
     
      MsgBox, 4, ,%msg%`nShutdown?, 90    ; give user 90 seconds to cancel shutdown
     
      IfMsgBox Timeout
         ShutDown()
         
      ifMsgBox Yes
         ShutDown()
         
      ifMsgBox No
         return
   }

   ;--- Ok lets back  up: Call your favorite imaging program here: I use "Image for Windows" console version
   MakeBootNowINI()     ; Update C:\windows\bootnow.ini so BootNow.exe can boot another OS to do the backup
   
   ;--- Shutdown, re-boot to a new OS and complete the backup there or use BootIt NG to image a set
   ;--- of partitions. Adjust the command as required.  See the user's manuals for details.
   ;--- The auto-run script in the other OS will image and then shut down.
   
   Run, bootnow.exe BU_Tools, C:\windows\system32\    ; This boots a second WinXP Pro partition called BU_Tools
                                                      ; Use gpedit.msc to run an auto start script to image,
                                                      ; log results and then shut down, all unattended.
   return
}

;###############################################################################################################
; Function to sync main and backup disks (File Back Up)
;###############################################################################################################

FileBackup()
{
   ;-------------------------------------------------------------------------------------------------------
   ; Create a "file type" back up on one of three rotating locations (i.e. keep three most recent versions)
   ; This script causes an incremental back up that takes about 10 minutes a day and copies the data files
   ; to one of three destination drives where they can be browsed in Windows Explorer
   ;-------------------------------------------------------------------------------------------------------

   Global CurrFlagDir
   
   SetWorkingDir, %CurrFlagDir%

   k := 99

   SyncList := "UVW"

   Loop, Parse, SyncList
   {
      ifExist, LastSync_%A_LoopField%.log
      {
         k := A_Index
         break
      }
   }

   NextFile = LastSync_U.log     ; initialize status counter
   
   if (k=99)
   {
      ;--- no previous record found
      k := 1
   }
   else
   {
      ;--- found previous status counter

      List1 = LastSync_U.log  ; create an array of counter names
      List2 = LastSync_V.log
      List3 = LastSync_W.log

      k := k+1               ; advance counter 

      if(k=4)                ; wrap counter
      {
         k:=1
      }

      NextFile := List%k%    ; name the next file
   }

   FileDelete, LastSync*.*   ; clean up
   FileAppend,,%Nextfile%    ; create new file to record bu that is about to happen

   ;-------------------------------------------------------------------------------------------------
   ; Call your favourite file sync program: I use GoodSync but the free xxcopy from Pixie Labs works
   ;-------------------------------------------------------------------------------------------------

   Job := "XXX"        ; Name of GoodSync backup job
   
   if(k=1)
   {
      Job := "Bu2U"    ; Back up to U:\
   }
   
   if(k=2)
   {
      Job := "Bu2V"    ; Back up to V:\
   }
   
   if(k=3)
   {
      Job := "Bu2W"    ; Back up to W:\
   }
   
   ;--- Select destination drive
   D := SubStr(SyncList,k,1)     ; Destination drive letter
     
   ;--- Make sure drive is turned on ... or quit
   CheckDrive(D)
   
   RunWait, goodsync.exe /exit sync %Job%, C:\Program Files\Siber Systems\GoodSync

   FileAppend,Resulting errorlevel for sync %Job% = %ErrorLevel%`n, %Nextfile%  ; Record exit code for sync program
   
   return
}

;#####################################################################################################
; Subroutine to Shut down the computer down
;#####################################################################################################

ShutDown()
{
   Global BackFile

   ;--- Log completion time
   buMsg = Completed Back up at %A_YYYY%-%A_MM%-%A_DD% %A_Hour%:%A_Min%:%A_Sec% `n

   FileAppend, %buMsg%, %Backfile% ; Log that is about to happen

   MsgBox, 4, , Shutdown?, 100     ; Give user 100 seconds to abort. Proceed if nobody is around

   Ans := 1                        ; var to code user response

   IfMsgBox Timeout                ; No one at the keyboard
      Ans := 1

   ifMsgBox Yes                    ; Shutdown was requested
      Ans := 1

   IfMsgBox No                     ; Stay running was requested
      Ans := 0

   ;--- Shutdown and power off
   
   If (Ans = 1)
   {     
      ;--- Shutdown
      MakeBootNowINI()                                 ; Find & record the drive where BootIt NG is installed
      Run, BootNow.exe /Shutdown, c:\windows\system32  ; Reboot and shut down
   }

   ;--------------------------------------------------------------------------------------
   ; Shutdown options: TSSHUTDN.EXE, BOOTNOW.EXE
   ; BootNow is very reliable and free from Terrabyte Unlimited. 
   ;    You need to create a BOOTNOW.INI, call MakeBootNowINI() before calling Bootnow.exe,
   ;    see the BOOTNOW readme. Use diskmgmt.msc to find the drive number where BING is stored
   ; TSSHUTDN.EXE is part of Windows XP Pro, Press Escape to abort
   ;--------------------------------------------------------------------------------------

   return
}

;#####################################################################################################
; Subroutine to manage and update status flag files
;#####################################################################################################

TrackStatus()
{
   Global PrevFlagDir
   Global CurrFlagDir
   Global BackFile
   
   ;--- Define location of status records
   SetWorkingDir, %CurrFlagDir%   

   ;--- Record previous state
   FileDelete, %PrevFlagDir%\Last*.*                       ; clean up destination before copy 
   FileCopy, %CurrFlagDir%\Last*.*, %PrevFlagDir%\*.*      ; record prev BU status in Prev Folder
   
   k := 99                            ; Variable to hold current step count

   BuIDList := "1234567890abcdef"     ; List of all possible backup counter values

   Loop, Parse, BuIDLisT              ; Search for filename identifying the previous count
   {
      ifExist, LastBack_%A_LoopField%.log
      {
         ;-- Found a file called eg "LastBack_6.log" or "LastBack_f.log")
         k := A_Index     ; return present position in the BuIDList
         break
      }
   }

   BackFile = LastBack_1.log  ; Initialize step counter

   if (k=99)
   {
      ;--- No previous record of back up
      k := 1                   ; start at the top of the cycle
   }
   else
   {
      ;--- Record of previous backup found
      k := k+1               ; advance counter 
      if(k=17)               ; wrap counter
         k:=1

      flag := SubStr(BuIDList,k,1)      ; Display value for status flag
      BackFile = LastBack_%flag%.log    ; filename the next backup counter (old ahk syntax used)
   }

   buMsg = Starting Back up initiated on %A_YYYY%-%A_MM%-%A_DD% %A_Hour%:%A_Min%:%A_Sec% `n

   FileDelete, LastBack*.*              ; clean up previous state flags
   FileAppend, %buMsg%, %BackFile%      ; create new file to record bu that is about to happen
   
   return k
}

;######################################################################################################
; Subroutines to manage image backups by deleting old backups, if required
;######################################################################################################

GetGB(FilePattern)
{
   ;--- Calculate the sum of file sizes for all files
   ;--- in a folder matching the FilePattern Var
   ;--- Calculate the sum in bytes and divide by 10**9
   
   Sum := 0
   
   Loop, %FilePattern%, , 0
       Sum += %A_LoopFileSize%
       
   return Sum/1000000000  ; sum of file sizes in GiB
}

MakeRoom(FilePattern,NextFile)
{
   Global QuotaGB 
   Global Min_GB
   
   Result := 0                                             ; Not ok to back up
   
   loop
   {
      FreeGB := 0                                          ; Var to hold space available on disk
     
      Drv := Substr(Filepattern,1,3)                       ; Destination drive letter eg W:\
     
      DriveSpaceFree, FreeGB, %Drv%                        ; get space available on disk
     
      FreeGB /= 1000                                       ; Change MB to GB
     
      CurrSize := GetGB(FilePattern)                       ; Total size of existing back up files 

      if ((CurrSize > QuotaGB) OR (FreeGB < Min_GB ))
      {
         ;--- Delete the oldest backup file

         FileList = ;                                                            ; Make a varaiable to hold list of back up files

         Loop, %FilePattern%, 1
             FileList = %FileList%%A_LoopFileTimeCreated%`t%A_LoopFileName%`n    ; Save list of file names and creation dates to a string

         Sort, FileList                                                          ; Sort by date, Oldest first

         if (StrLen(FileList) < 1)
         {
            ;--- no back ups left to delete!
            Result := 0
            break
         }

         FileName =                                                             ; Var to hold name of file to be deleted

         Loop, parse, FileList, `n                                              ; Get first file name on list
         {
             StringSplit, FileItem, A_LoopField, %A_Tab%                        ; Split into two parts at the tab char.
             FileName := FileItem2                                              ; Save the name
             break
         }   

         StringTrimRight, Path, FilePattern, 7                                  ; Path to target file

         Target = %Path%%FileName%                                              ; Pattern to delete

         FileAppend, MakeRoom() deleted image file "%Target%"`n,%NextFile%      ; log delete

         FileDelete, %Target%                                                   ; Ok! One image file gone
      }
      else
      {
         Result := 1
         break
      }
   }
   return Result
}

;######################################################################################################
; Subroutines to find out where BootIt NG is installed and fix BOOTNOW.INI
;######################################################################################################


MakeBootNowINI()
{
   ;---------------------------------------------------------------------------------------------------
   ; This reoutine is required because Windows changes the disk enumeration from time to time.
   ; When HD sequence numbers change BOOTNOW.EXE cannot find the home partition.
   ; This routine finds the HD containing BING and then writes a BOOTNOW.INI file telling BOOTNOW.EXE
   ; where to find BING. See the ReadMe that comes with the free BOOTNOW.EXE download
   ;---------------------------------------------------------------------------------------------------

   Global BingName   ; Name of partition where you installed BootIt NG

   ;--- Local variables required, Patch as required
   IFWfile  := "C:\Windows\IFW_Info.txt" ; Will contain the result of C:>imagew.exe /L
   bnFile   := "C:\windows\bootnow.ini"  ; File read by bootnow.exe to locate BootIt NG
   msg      := "Not Found"
   result   := 0
   
   ;--- Create a text file listing the HD numbers and partitions using Image for Windows
   RunWait, %comspec% /C imagewc.exe /L > "%IFWfile%", C:\Program Files\TeraByte Unlimited\Image for Windows\V2\
   
   ;--- Search the list of files to see where Bootit NG is installed
   ;--- BootNow.exe needs to know where BING is located
   ifExist, %IFWfile%
   {
      topline := 0
      Loop
      {
          topline += 1
          FileReadLine, line1, %IFWfile%, topline
          FileReadLine, line2, %IFWfile%, topline+1
          FileReadLine, line3, %IFWfile%, topline+2
          FileReadLine, line4, %IFWfile%, topline+3
          FileReadLine, line5, %IFWfile%, topline+4
         
          if ErrorLevel
          {
              ;--- EOF encountered
              result = 0
              break
          }

          if (instr(line5,BingName))    ; BootIt NG is installed in this partition
          {
             msg = %line1%
             result = 1
             break
          }
      }

      if(result = 1)
      {
         ;--- Write a new bootnow.ini file with new HD number
         disknum := substr(msg,3,1)
         msg = [OPTIONS]`nhd=%disknum%
         FileDelete, %bnFile%
         FileAppend, %msg%, %bnFile%
         result := errorlevel
      }
     
      FileDelete, %IFWfile%
   }
   return result     ;--- Now you can call BootNow.EXE and it will re-boot to the target OS reliably
}


Code:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; SCRIPT #2:
;
;
; Note: Chage the extension on this file from .txt to .ahk before running it.  It was posted
;       as .txt for security reasons.
;
; This script is the the second of two. The first is run in the normal working instance of windows where the first script
; will point to the next disk to receive an image file, reboot to a second instance of Windows.  The second instance of Windows
; will run this script which creates the image back up. After the image is created, this script shuts the computer down.
;
; In the main working instance of Windows, place short cut on your desk top calling the first script. At the end
; of the day doule click the shortcut and walk away.  Your computer will image to one of three rotating locations
; and then power down.
;
; Script #2 runs as a GPO (gpedit.msc) startup script . It will back the computer up and shut it down. You
: must run Script #1 on the first instance of windows which will boot to a second instance of Windows. This
; script is meant to run on the second instance of Windows unattended.
;
; Modify the script as required and test it after logging on as a user with administrative rights. To install,
; launch gpedit.msc, drag the script to the "Show Files" windows in Computer Configuration | Windows Settings
; | Scripts | Start Up.
;
; Important:
; While in gpedit.msc, scroll to User Configuration | Administrative Templates | System | Scripts
; and set "Maximum wait time for Group Policy Scripts" to a value longer than a backup will take.  Otherwise
; your script will be terminated, and the machine shut down, after the default 600 seconds.  You can also
; set the value to 0 which means infinity.  See CC757265 on MS Technet.
;
; This script provides a 20 second window at boot time so that you can abort the back up and log normally to the
; second instance of Windows.  From here you can do anything you want including modify Script #2.
;
; You Need:
; --------
;  Autohotkey, free from www.autohotkey.com. See See http://www.autohotkey.com/docs/commands.htm
;     for a list of commands
;
;  BootIt NG,  from www.terabyteunlimited.com.  Not free but very reliable and inexpensive.  Aka BING.
;  BootNow.exe free from Terrabye Unlimited.
;
;  Imaging software: I recommend Image for Windows www.terabyteunlimited.com.  Not free but very reliable and
;     inexpensive.  Aka IFW.  You can down load a console version, IFWC.exe, that is ideal for scripting. If
;     you buy BING you may not need imaging software.  It can create images all by itself and can be batched.
;     Use version 1.99 of TBIview (a Windows Program) to extract files one at a time, from the BING created image.
;
;  File backup software: I like GoodSync, www.goodsync.com. There is a console version, gsync, that is
;     ideal for scripting. There are many other free options such as xxcopy from Pixie labs,
;     http://www.xxcopy.com/index.htm is an ecellent choice.
;  Any text editor
;
; One Way to create a second instance of Windows:
;  Boot the recovery disk that came with your partitioning software.  I greatly prefer BING to Partition Magic.
;  Create a small (20 - 30 MB) partition and install a boot manager.  I greatly prefer BING to BootMagic.
;  Use the partitioning software to create a new partition of 16 GB or larger. Restore or copy a previous
;  image of Windows to the new partition, or just reinstall from your Windows CD.  You might have to resize
;  the existing partitions before installing a second instance of Windows.  Take the usual precautions when
;  running the second instance of windows: I turn off System restore and disable the indexing service.
;
;  Whenever I install Windows, I make an image of the installation after all updates are applied and before
;  any application software is installed. This image is used whenever another instance of Windows is required
;  on that computer.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

#NoEnv                   ; Not using vars in the Windows environment

MsgBox,4,,Back Up?,20    ; 20 second timeout, then back up   

ifMsgBox No
{
   exit                  ; return to windows
}


;--- Define Global vars
CurrState = N:\Documents and Settings\Al\Desktop\Shutdown_BU\BU Tools       ; Location of status files for current back up
PrevState = N:\Documents and Settings\Al\Desktop\Shutdown_BU\BU Tools\Prev  ; location of status files for previous back up

MakeImage()         ; Do a complete back up using disk imaging software

ShutDown()          ; Power down

return              ; End of main routine.  Subroutines below.
 

;==========================================================================================
; Function to make sure back up drives are turned on/available or quit
;==========================================================================================

CheckDrive(D,LogFile)
{
   Global PrevState
   Global CurrState
   
   ifExist,%D%:\       ; D is the argument passed to CheckDrive()
      DrvUp := 1
   else
      DrvUp := 0
   
   if NOT DrvUp
   {
      MsgBox,0,,Turn Backup Drive %D%: On, 20
     
      loop
      {
         if (A_Index > 3)
    {
            FileDelete, %CurrState%\Last*.*                  ; clean up destination before copy 
            FileCopy, %PrevState%\Last*.*, %CurrState%\*.*
            msg = *** Back up Cancelled *** Drive %D%:\`n not available`n
            Fileappend, %msg%, %LogFile%
            exit                                             ; return to Windows
         }

         RunWait devcon rescan   

         Sleep 5000
   
         ifExist,%D%:\                                       ; D is the argument passed to CheckDrive()
         {
            break
         }
      }
   }   
   return
}

;=======================================================================================================================
; Function to create an image (Complete) back up
;=======================================================================================================================

MakeImage()
{
   ;---------------------------------------------------------------------------------------------------
   ; Create a disk image on one of three rotating locations (i.e. keep at least 3 most recent versions)
   ;---------------------------------------------------------------------------------------------------
   
   ;--- Update imag counter
   
   Global CurrState   

   SetWorkingDir, %CurrState%   

   List1 = LastImag_U.log      ; create an array of valid counter names
   List2 = LastImag_V.log     
   List3 = LastImag_W.log

   NextFile = LastImag_U.log   ; Initialize backup status flag
                               ; The previous OS updated the file to
                               ; point to the drive to recieve the image
   k := 99

   ifExist %List1%
       k := 1
   
   ifExist %List2%
       k := 2
   
   ifExist %List3%
       k := 3

   if (k = 99)                 ; No previous back found
       k := 1                 

   ;--- Select destination drive
   ImagList := "UVW"
   Drv := SubStr(ImagList,k,1)   ; Destination drive letter
   CheckDrive(Drv,NextFile)      ; Make sure BU Drive is turned turned on...or exit.

   NextFile = LastImag_%Drv%.log

   ;--- Create dated names for the image files
   fn1 = BU %A_YYYY%-%A_MM%-%A_DD% BING  80GB_IDE_Mode_ahk
   fn2 = BU %A_YYYY%-%A_MM%-%A_DD% HOM   80GB_IDE_Mode_ahk
   fn3 = BU %A_YYYY%-%A_MM%-%A_DD% WinXP 80GB_IDE_Mode_ahk
   fn4 = BU %A_YYYY%-%A_MM%-%A_DD% DATA  80GB_IDE_Mode_ahk

   ;--- Ok lets back  up: Call your favorite imaging program here: I use "Image for Windows" console version

   idir := "C:\Program Files\TeraByte Unlimited\Image for Windows\V2"           ; Starting directory for IFWC.EXE

   RunWait, imagewc.exe /b /d:?O:  /f:"%Drv%:\%fn1%" /uy /v /vb, %idir%          ; Back up BING
   FileAppend,Resulting Errorlevel for %fn1% = %ErrorLevel%`n, %Nextfile%        ; Record exit code for imaging program


   RunWait, imagewc.exe /b /d:?L:  /f:"%Drv%:\%fn2%" /uy /v /vb, %idir%          ; Back HOM (Hidden Offline Maintenance)
   FileAppend,Resulting Errorlevel for %fn2% = %ErrorLevel%`n, %Nextfile%         

   RunWait, imagewc.exe /b /d:?M:  /f:"%Drv%:\%fn3%" /uy /v /vb, %idir%          ; WinXP_Main
   FileAppend,Resulting Errorlevel for %fn3% = %ErrorLevel%`n, %Nextfile%         
 
   RunWait, imagewc.exe /b /d:?N:  /f:"%Drv%:\%fn4%" /uy /v /vb, %idir%          ; Back DATA
   FileAppend,Resulting Errorlevel for %fn4% = %ErrorLevel%`n, %Nextfile%         

   return
}

;=======================================================================================================
; Subroutine to Shut down the computer down
;=======================================================================================================

ShutDown()
{

   MsgBox, 4, , ShutDown(): Shutdown?, 20     ; Give user 100 seconds to abort. Proceed if nobody is around

   Ans := 1                        ; var to code user response

   IfMsgBox Timeout                ; No one at the keyboard
      Ans := 1

   ifMsgBox Yes                    ; Shutdown was requested
      Ans := 1

   IfMsgBox No                     ; Stay running was requested
      Ans := 0

   ;--- Shutdown and power off
   
   If (Ans = 1)
   {     
      ;--- Shutdown

      ;--- An option: Run, %comspec% /C tsshutdn.exe 30 /POWERDOWN /DELAY:30, c:\windows\system32

      MakeBootNowINI()                                 ; Get HD# for BootNow
      Run, BootNow.exe /Shutdown, c:\windows\system32  ; Shutdown using BootNow

   }

   ;--------------------------------------------------------------------------------------
   ; Shutdown options: TSSHUTDN.EXE, DEVCON.EXE, BOOTNOW.EXE
   ; BootNow is very reliable and free from Terrabyte Unlimited. 
   ;    You need to create a BOOTNOW.INI. See the BOOTNOW readme.
   ;    Use diskmgmt.msc to find the drive number where BING is stored
   ; TSSHUTDN.EXE is part of Windows XP Pro, Press Escape to abort
   ;--------------------------------------------------------------------------------------

   return
}

;######################################################################################################
; Subroutines to find out where BootIt NG is installed and fix BOOTNOW.INI
;######################################################################################################

MakeBootNowINI()
{
   ;---------------------------------------------------------------------------------------------------
   ; This reoutine is required because Windows changes the disk enumeration from time to time
   ; When HD sequence numbers change BOOTNOW.EXE cannot find the home partition.
   ; This routine finds the HD containing BING and then writes a BOOTNOW.INI file telling BOOTNOW.EXE
   ; where to find BING. See the ReadMe that comes with the free BOOTNOW.EXE download
   ;---------------------------------------------------------------------------------------------------

   ;--- Local variables required
   msg     := "Not Found"
   result  := 0
   rfile   := "C:\IFW_info.txt"
   
   ;--- Create a text file listing the HD numbers and partitions
   RunWait, %comspec% /C imagewc.exe /L > "%rfile%", C:\Program Files\TeraByte Unlimited\Image for Windows\V2\
   
   ;--- Search the list of files to see where Bootit NG is installed
   ;--- BootNow.exe needs to know where BING is located
   ifExist, %rfile%
   {
      topline := 0
      Loop
      {
          topline += 1
          FileReadLine, line1, %rfile%, topline
          FileReadLine, line2, %rfile%, topline+1
          FileReadLine, line3, %rfile%, topline+2
          FileReadLine, line4, %rfile%, topline+3
          FileReadLine, line5, %rfile%, topline+4
         
          if ErrorLevel
          {
              ;--- EOF encountered
              result = 0
              break
          }

          if (instr(line5,"BING"))    ; BootIt NG is installed in this partition
          {
             msg = %line1%
             result = 1
             break
          }
      }

      if(result = 1)
      {
         ;--- Write a new bootnow.ini file with new HD number
         disknum := substr(msg,3,1)
         msg = [OPTIONS]`nhd=%disknum%
         bfile = C:\windows\bootnow.ini
         
         FileDelete, %bfile%
         FileAppend, %msg%, %bfile%
         result := errorlevel
      }
   }
   return result     ;--- Now you can call BootNow.EXE and it will re-boot to the target OS reliably
}


_________________
Image
(Common Answers) - New Tutorials Forum - Humongous FAQ


Report this post
Top
 Profile  
Reply with quote  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 2 posts ] 

All times are UTC [ DST ]


Who is online

Users browsing this forum: Scratch and 15 guests


You can post new topics in this forum
You can reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Search for:
Powered by phpBB® Forum Software © phpBB Group