Solved

Backup Script

Posted on 2008-06-15
9
447 Views
Last Modified: 2013-12-01
I need 2 scripts.

1.  I plug in my external drive. Double Click on something(like a .vbs). And automatically backup everything that user needs before i wipe it.(I believe that would be the documents and settings folder)
2. I plug in my external drive. Double Click something. And automatically everything is restored.(My documents,- word docs, ppts, pics,etc, that was on there desktop-,IE Favorites, Firefox Favorites)
0
Comment
Question by:zbox
  • 3
  • 3
  • 2
  • +1
9 Comments
 
LVL 3

Accepted Solution

by:
callmecheez earned 500 total points
ID: 21789940
You'd be surprised how good the files and settigns transfer wizard in Windows it:
(info here:)
http://www.microsoft.com/windowsxp/using/setup/expert/crawford_november12.mspx

Other option is maybe disk imaging software:
Paid, but good:
Acronis Trueimage
http://www.acronis.com/homecomputing/products/trueimage/

Free, and apparently okay:
DriveImage XML: http://www.runtime.org/driveimage-xml.htm
iRestorer: http://irestorer.parsaspace.ir/


Hope this is of some help.
0
 
LVL 31

Expert Comment

by:Frosty555
ID: 21790018
So who's to stop the client from saving important personal data in C:\Joe's Cool Stuff?

Or what if they downloaded a cd ripping program that stores the ripped files in C:\Program Files\AwesomeRipperPro\output ?

Restoring a user's personal files after wiping their computer is a manual task. Typically the My Documents, Favourites, and a couple other minor things cna be done automatically, but everything else has to be done by hand.

For that reason, it is crucially important you have a FULL bare metal backup of the computer before you start reformatting it. That way, when the client comes back two weeks later in a panic because they just realized half their music collection was actually not in the My Music folder, or that their entire company financial records was stored in the \Program Files\Quickbooks folder, you have the data and don't get into a mess.

That said, I do two. First I use driveimage xml to make an image-based backup. DriveImageXML is great if you need to restore windows in it's full glory - boot record and all.

Then I use robocopy to make a file-level backup of every file. I just do the latter so that it is fairly painless to copy the files back later. Again, with robocopy.
0
 
LVL 24

Expert Comment

by:purplepomegranite
ID: 21792910
I use the attached code to set-up backup for clients - a script I wrote.

If you put it on a USB drive, you need two other files:

backup.cmd:
cscript backup.vbs

autorun.inf:
[autorun]
action="Backup Documents and Settings"
open=backup.cmd


Save the files above (they are just normal text files just rename as shown), then when you insert the USB drive you are offered the option to backup.  By default it copies everything in the Documents and Settings folder to a backup folder on the USB drive.

So that is part 1 of your question.  Part 2 should actually be another question.  However, the code below can easily be modified to do part 2 too.

The advantage of using the script below (in my opinion) is that it doesn't crash (any errors it will just carry on), it doesn't copy files that don't need copying (so runs much quicker after the first copy), and saves the files in a way easily recoverable (i.e. doesn't need third party software to read an image file).
' Backup Script
 

'on error resume next
 

' Logging levels:

' 0 = no logging

' 1 = log failures only

' 2 = log everything
 

Const ForReading = 1, ForWriting = 2, ForAppending = 8

Const vbReadOnly = 1, vbHidden = 2, vbSystem = 4, vbVolume = 8

Const vbDirectory = 16, vbArchive = 32, vbAlias = 64, vbCompressed = 128
 

dim loggingLevel

dim sourceFolder, targetFolder

dim logFile

dim filesChecked

dim filesCopied

dim foldersChecked

dim filesFailed
 

' Read backup parameters
 

set fso=CreateObject("Scripting.FileSystemObject")
 

if WScript.Arguments.Count=0 then

	' No arguments - assume running on USB drive and set defaults

	USBAutoConfigure

	WScript.echo sourceFolder

	WScript.echo targetFolder

	'WScript.Quit

else

	sourceFolder=WScript.Arguments.Item(0)

	targetFolder=WScript.Arguments.Item(1)

	if WScript.Arguments.Count>3 then

	   loggingLevel=WScript.Arguments.Item(2)

	   logFile=WScript.Arguments.Item(3)

	else

	   loggingLevel=0

	end if

end if
 
 
 
 

' Create/open log file
 

if loggingLevel>0 then

   if not fso.FileExists(logFile) then

      set logFileTS=fso.CreateTextFile(logFile,false)

      if err.number<>0 then

         err.clear

         loggingLevel=0

      end if

   else

      set logFileTS=fso.OpenTextFile(logFile,ForAppending)

      if err.number<>0 then

         err.clear

         loggingLevel=0

      end if

   end if

end if
 

if loggingLevel>0 then

	logFileTS.WriteLine

	logFileTS.WriteLine "Backup started: " & Now

	logFileTS.WriteLine "Source: " & sourceFolder

	logFileTS.WriteLine "Target: " & targetFolder

	logFileTS.WriteLine "Logging Level: " & loggingLevel

	logFileTS.WriteLine

end if
 

filesChecked=0

foldersChecked=0

filesFailed=0

filesCopied=0

CopyFolder sourceFolder, targetFolder
 

if loggingLevel>0 then

	logFileTS.WriteLine

	logFileTS.WriteLine "Backup finished: " & Now

	logFileTS.WriteLine "Total folders backed up: " & foldersChecked

	logFileTS.WriteLine "Total files checked: " & filesChecked

	logFileTS.WriteLine "Total files copied: " & filesCopied

	logFileTS.WriteLine "Total files failed: " & filesFailed

	logFileTS.WriteLine

end if
 
 

logFileTS.Close

set fso=nothing

WScript.Quit
 
 

Sub CopyFolder(sourceFolder, targetFolder)

    ' Copies the source folder to the destination folder...

	dim dirList()

	dim sourceFolderObject

	dim f

    dim firstRedim

	

    On Error Resume Next

	

	foldersChecked=foldersChecked+1

	

    If InStr(1, targetFolder, sourceFolder, vbTextCompare) > 0 Then

	    if not (mid(sourceFolder, 2,1)=":" and mid(targetFolder,2,1)=":" and Left(sourceFolder,1)<>left(targetFolder,1)) then

           ' Source folder is the target folder... don't copy! (or recursion will kick in badly...)

		   AddLog "Target folder same as source folder... process halted", 1

           Exit Sub

		end if

    End If

    

    firstRedim = True

    

    If Right(sourceFolder, 1) <> "\" Then sourceFolder = sourceFolder & "\"

    If Right(targetFolder, 1) <> "\" Then targetFolder = targetFolder & "\"

    

    If Not fso.FolderExists(Left(targetFolder, Len(targetFolder) - 1)) Then

        BuildPath targetFolder

    End If

    

    ' Get list of directories

    set sourceFolderObject=fso.GetFolder(Left(sourceFolder, Len(SourceFolder)-1))

	for each f in sourceFolderObject.SubFolders

        If f.Name <> "." And f.Name <> ".." Then

			' Add directory to dirList

			If firstRedim Then

				ReDim dirList(0)

				firstRedim = False

			Else

				ReDim Preserve dirList(UBound(dirList) + 1)

			End If

			dirList(UBound(dirList)) = f.Name

		End If

    Next

    

    

    ' Now copy files

	if sourceFolderObject.Files.Count>0 then

		for each f in sourceFolderObject.Files

	            ' Copy this file (if different from target folder)!

	        If FilesDiffer(sourceFolder & f.Name, targetFolder & f.Name) Then

	            ' Files don't match, so copy

	            If Not fso.FolderExists(targetFolder) Then BuildPath targetFolder

	            fso.CopyFile sourceFolder & f.Name, targetFolder & f.Name, True

	            If Err.Number = 0 Then

	                FilesCopied = FilesCopied + 1

	                AddLog "Copied " & sourceFolder & f.Name, 2

	            Else

	                AddLog "FAILED TO COPY (" & Err.Description & ") " & sourceFolder & f.Name, 1

					filesFailed=filesFailed+1

	                Err.Clear

	            End If

	        Else

	            AddLog "Skipped " & sourceFolder & f.Name, 2

	        End If

	    next

	end if

    

    ' Now recurse directories

    If Not firstRedim Then

        ' Directories need copying

        For i = 0 To UBound(dirList)

            CopyFolder sourceFolder & dirList(i), targetFolder & dirList(i)

        Next

        End If

    If Err.Number <> 0 Then Err.Clear

    

    

End Sub
 
 
 

Private Function FilesDiffer(sourceFile, targetFile)

    ' Returns true is the given files are different

	dim same, sf, tf

	

    On Error Resume Next

    

    filesChecked=filesChecked+1

	same = True

    

    Set sf = fso.getfile(sourceFile)

    Set tf = fso.getfile(targetFile)

    

    If Err.Number <> 0 Then

        ' File not present, so need to copy!

        Err.Clear

        same = False

    Else

        If sf.Size <> tf.Size Then same = False

        If sf.DateLastModified > tf.DateLastModified Then same = False

    End If

    

	set sf=nothing

	set tf=nothing

    

    FilesDiffer = Not same

    

    Err.Clear ' Just to make sure we're not passing any error messages back

    

End Function
 
 
 

Public Sub BuildPath(path)

    ' Builds the specified path.  Starts from the lowest level, creating each

    ' directory in turn.

    

    On Error Resume Next

        

    i = 1

    If Left(chkPath, 2) = "\\" Then i = 2

    Do

        chkPath = PathDepth(path, i)

        If Not fso.FolderExists(chkPath) Then

            ' Folder needs creating

            fso.CreateFolder chkPath

            End If

        i = i + 1

    Loop Until fso.FolderExists(path) Or Err.Number <> 0

    

    If Err.Number <> 0 Then Err.Clear

    

End Sub
 

Private Function PathDepth(FullPath, RequiredDepth)

    ' Returns the path to the specified depth

    ' (e.g. c:\1\2\3\4\, 1 will return c:\1 )

    

    On Error Resume Next

    

    If Left(FullPath, 2) = "\\" Then CutOffPoint = 2

    For i = 0 To RequiredDepth

        CutOffPoint = InStr(CutOffPoint + 1, FullPath, "\")

        If CutOffPoint = 0 Then Exit For

    Next

    If (CutOffPoint = 0) Or (Err.Number <> 0) Then

        Err.Clear

        PathDepth = FullPath

    Else

        PathDepth = Left(FullPath, CutOffPoint - 1)

        End If

End Function
 
 

Sub AddLog(LogText, LogLevel)

    ' Adds a log entry
 

    ' Check we should be logging this entry...

    wscript.echo LogText

    if loggingLevel<=LogLevel then exit sub

        

    ' Add to log file

    On Error Resume Next

            

    logfileTS.Writeline LogText

    If Err.Number <> 0 Then Err.Clear

End Sub
 

sub USBAutoConfigure

	' Determine backup location based on script location

	strDrive=Left(WScript.ScriptFullName,InStr(1, WScript.ScriptFullName, ":"))

	targetFolder=strDrive & "\Backup\Documents and Settings"

	

	' Determine source location based on Docs & Settings folder - doesn't support redirection yet

	set WshShell = WScript.CreateObject("WScript.Shell")

	set oWSH    = CreateObject("WScript.Shell")

	sAllUsersProfile    = oWSH.ExpandEnvironmentStrings("%ALLUSERSPROFILE%")

	set oWSH=nothing

	Set oAllUsersFolder = fso.GetFolder(sAllUsersProfile)

	sProfilesRoot       = oAllUsersFolder.ParentFolder

	sourceFolder=sProfilesRoot

	

	' Set logging

	loggingLevel=1

	logFile=strDrive & "\backup log.txt"

end sub

Open in new window

0
 
LVL 24

Expert Comment

by:purplepomegranite
ID: 21792954
Though it must be said, I agree with Frosty555's comments in this case.  If you are wanting to use this kind of thing before wiping a computer, you need a full image - you cannot presume that everything you need is under Documents and Settings.  Or anywhere, in fact.  I'm often amazed where people put things, and also where little known programs or such store their configuration data (and of course, it's too late to check these things once the machine is wiped...).

While the above script could also be reconfigured to backup the whole drive, it would fail at any files that are locked (where imaging software wouldn't).  So the backup couldn't be considered complete.
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 31

Expert Comment

by:Frosty555
ID: 21796826
Yeah, the script above can be considered a time-saving utility, but not a rigorous backup by any means.

Still though, I just use robocopy to copy the whole hard drive. It's real easy:

ROBOCOPY C:\ E:\Backups\SomeClient\CDrive /e /zb /r:3 /w:5 /v /eta /XD "Temporary Internet Files" "C:\Recycler" /XF "pagefile.sys" "hiberfil.sys"

That copies everything from the C drive, retries up to three times per file but persists through if it fails, and doesn't copy the Temporary Internet Files, Recycling Bin, or pagefile/hibernation files.
0
 
LVL 24

Expert Comment

by:purplepomegranite
ID: 21798138
Though Robocopy also fails on locked files, which can be a major issue when doing a full-system backup.  For example, database files will often be locked if a program is accessing them... yet they contain a lot of data, and are definitely files that need to be copied.  So for a true backup, I would say you need a utility that backs up with shadow copy, or force a reboot to ensure it can back up the files e.g. TrueImage or similar.
0
 

Author Comment

by:zbox
ID: 21810103
Hey thanks so much for all the great responses. Please allow me sometime to review the different solutions and ill respond asap.
0
 

Author Comment

by:zbox
ID: 21904535
Hey great advice all.  I now have acronis true image, which I can use to backup.  I don't to image though. If someone had a virus i wouldn't want to image a partition with a virus on it(callmecheez)

good point frosty, I figured I'd end up checking the root no matter what :-\   but yea robocopy should work pretty well and if not ill definately end up using it for something.

still figuring that script out pomegranite. looks pretty cool and thanks for the heads up on the database thing, im working on my access skills now.

but great point callmecheez  i had no idea the file and transfer wizard was that robust.

0
 

Author Closing Comment

by:zbox
ID: 31467411
the file and transfer wizard is pretty nice.
0

Featured Post

Give your grad a cloud of their own!

With up to 8TB of storage, give your favorite graduate their own personal cloud to centralize all their photos, videos and music in one safe place. They can save, sync and share all their stuff, and automatic photo backup helps free up space on their smartphone and tablet.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

How to fix error ""Failed to validate the vCentre certificate. Either install or verify the certificate by using the vSphere Data Protection Configuration utility" when you are trying to connect to VDP instance from Vcenter.
Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
This tutorial will walk an individual through configuring a drive on a Windows Server 2008 to perform shadow copies in order to quickly recover deleted files and folders. Click on Start and then select Computer to view the available drives on the se…
This tutorial will walk an individual through setting the global and backup job media overwrite and protection periods in Backup Exec 2012. Log onto the Backup Exec Central Administration Server. Examine the services. If all or most of them are stop…

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now