VMware Communities > VMTN > VMware Server™ > VMware Server 1 > Documents

Advanced VB script for backup of VMs on Windows hosts

VERSION 1 Published

Created on: Mar 26, 2008 6:39 AM by jim.patrick - Last Modified:  Mar 26, 2008 6:40 AM by jim.patrick

Please advice. I worked about 5 days on it, and it's awesome, IMHO.

Read the leading comment attentively. Save the code as vm-backup.vbs. Enjoy. Share your comments.

code
' Copyleft saxa aka Alexander Kaufmann, 2006
'
' Written just for fun; total Open Source.
' Use it at your own risk.
'
' The script uses the VmCOM API for the virtual machine operations.
'
' The virtual machine *must* have the VMware Tools installed, in order to perform the
' shutdown and heartbeat operations correctly.
'
' DON'T APPLY THIS SCRIPT ON RUNNING VIRTUAL MACHINES WHICH DON'T HAVE THE VMWARE TOOLS INSTALLED.
'
' It works on Windows 2000 SP4 and newer; it doesn't use the NTBackup utility.
'
' The script runs on the local host only; it cannot be used to connect to a remote VMware Server.
' The script *can* backup to the network share, if you have the appropriate permissions to do it.
'
' For the backup jobs it uses the command line version of 7zip: get it on http://7zip.org/download.html.
' You need the "7-Zip Command Line Version". Or, just download the full install - there is also a 64 bit
' version available.
'
' We assume that the 7zip executable is included in your %PATH% variable.
' Most probably you already have a folder with your tools, where you will also save this script.
' We have on each of our servers the folder C:\Program files\myTools created and it is added to %PATH%.
'
' Please see Windows Help on how to add a folder to %PATH%.
'
' Here I go again (c) ;))
'
' To use the command line version of this script (non-interactive mode):
' We assuming that all of our .vmx files are named vm.vmx.
' The name itself doesn't matter, but it must be the same for every virtual machine.
' If you don't like vm.vmx, please change the following variable correspondingly.

vmfile = "vm.vmx"

' We also assume that all of your virtual machines are located in the appropriate subdirectories
' of *one* directory; in other words, we need a flat structure.
' See the variable "vmpath" and change it to your needs.
' Here is a sample of correct directory layout:
'
' D:\Virtual Machines\
' Virtual Machine 1\
' vm.vmx
' hdd1.vmdk
' hdd1-flat.vmdk
' hdd2.vmdk
' hdd2-flat.vmdk
' other_file.ext
' Virtual Machine 2\
' vm.vmx
' disks\
' some weird disk 1.vmdk
' some weird diskette.flp
'
' As you can see, subdirectories are also allowed. It's only important that your .vmx file is placed
' on the (in this sample) second level, say, the full path to .vmx must be
' D:\Virtual Machines\Virtual Machine X\vm.vmx for every virtual machine.
'
' The subdirectory where the virtual machine is located is very important for this script:
' it's the virtual machine's identifier.
' In our sample these are "Virtual Machine 1" and "Virtual Machine 2" respectively.
'
' You will start the script as follows:
'
' vm-backup.vbs "Virtual Machine 1"
'
' or
'
' vm-backup.vbs "Virtual Machine 2"
'
' to backup the Virtual Machine 1 or Virtual Machine 2.
'
' If you want to use the script in a sheduled task, you must use the following command line:
'
' wscript.exe vm-backup.vbs "Virtual Machine 1"
'
' to backup the Virtual Machine 1.
'
' The script does the following:
'
' The virtual machine gets the command to shut down it's operating system.
' The script waits 30 seconds and than checks the state of the virtual machine.
' If the vm still runs, the script waits 30 seconds more and so on.
' As soon as the vm is off, the script copies the vm's folder into the backup location
' (see the "bkpath" variable and change it if you would like to; UNC paths are accepted).
'
' If the vm couldn't be shut down, the mail is sent to the admin,
' the error is written in the Windows application log.
'
' After the copying is done, the vm receives the command to start, if it was running before the operation has begun.
' 30 seconds later, and then every 30 seconds, the script checks the heatbeat of the vm.
' As soon as the vm at 300 or more units of heartbeat, the script starts to create
' a compressed archive from a previously copied vm directory.
' At that point of time is the vm already up and running.
' A .zip archive receives the following name: YYYY-MM-DD-HHMMSS-Virtual Machine 1.zip
' The creation of the .zip file takes it's time: on Pentium 4 (with Hyperthreading, single core)
' 2.8 GHz machine with 3 GB RAM is the duration of compress operation on a virtual machine
' having 2 virtual HDDs at 16 and 36 GB was about 2 hours. Though it is worth the effort:
' the resulting file has the size of 3.6 GB: compare it to 52 GB uncompressed .
' So, after the .zip file is ready, the script checks if there were any errors produced by 7zip.
' If there are some, the Windows Application log is misused for the registration of them.
' If not, then we can safely delete the copy of the vm used as a source for compression
' and create the record of successful backup operation in the Application log.

' The interactive mode (if you start the script without any parameters) does the same.
' You can manually name your zip file.

' Added on 2006-10-16; now is in Beta-Testing

' It's also possible to run a script as following (quite interesting for "scripting of this script"):

' vm-backup.vbs "X:\Full Path To vmx File\My vmx file.vmx" "Y:\Full Path To Some zip File\bla\Any name.zip"

' The script will backup the directory "X:\Full Path To vmx File\" including all subdirectories.

' Why it's Beta:
' The script will *not* create the directory ""Y:\Full Path To Some zip File\bla\"

vmpath = "D:\Virtual Machines\"

' Please don't forget the ending backslash!
' vm -> Directory where the VM files are located: the machine name is received from the argument.

' bkpath -> Destination directory; here are temporary backups created,
' and here you will find your .zip files.
' The user who runs the script must have the write permissions on directory / network share.

bkpath = "E:\backups\"

' In the variable seven_zip_switch you can provide the additional switches for the command line of 7zip.
' The most thinkfully switch is " -v4g" (don't forget the leading space!). It causes the splitting of your
' archive into volumes at 4 GB. Please read the 7zip's manual about the -v switch.

seven_zip_switch = ""

adminmail = "mail@domain.com" 'Here you'll receive mail messages.

smtp = "smtp.domain.com" 'Your SMTP server must be able to relay the mails for your mail address. IP address is also OK.


On Error Resume Next

' Common definitions...

Set wshShell = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
Set cp = CreateObject("VmCOM.VmConnectParams")
Set server = CreateObject("VmCOM.VmServerCtl")
Set thevm = CreateObject("VmCOM.VmCtl")
Set wshNet = CreateObject("WScript.Network")
Set mailing = CreateObject("CDO.Message")

mailing.From = lcase(wshNet.UserName & "@" & wshNet.ComputerName & "." & wshNet.UserDomain)
mailing.To = adminmail
mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = smtp
mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25

header = "Backup Script for VMware Virtual Machines" 'Just the title for message boxes...

Function iso_date(byval dt)

' The function does nothing interesting...

dim y: y=year(dt)
dim m: m=month(dt)
dim d: d=day(dt)
dim h: h=hour(dt)
dim n: n=minute(dt)
dim s: s=second(dt)

if m < 10 then m="0" & m
if d < 10 then d="0" & d
if h < 10 then h="0" & h
if n < 10 then n="0" & m
if s < 10 then s="0" & s

iso_date = y & "-" & m & "-" & d & "-" & h & n & s

end Function

' Here we are getting the name of the VM delivered by the script argument; it must one or two.
' If there are two, it means, user want to define the VM and backup location manually.
' If there are more than two, it's an incorrect call.

Set args = WScript.Arguments

If args.Count=1 Then 'We are in the mode with predefined vm by parameter, way = "a(utomatic)"
vm = args(0)
vmfolder = vmpath & vm
vmfile = vmfolder & "\" & vmfile

zipfile = bkpath & vm & "-" & iso_date(now) & ".zip"

tmpfolder = bkpath & vm

way = "a"

ElseIf args.Count=0 Then 'We are in the interactive mode, way = "i(nteractive)"

vmfile = inputBox("Please enter the full path to the .vmx file of the virtual machine you want to backup:",header,vmpath)

' Quit if cancel

if vmfile = "" then

WScript.Quit

end if

vmfolder = fso.GetParentFolderName(vmfile)

vmparent = fso.GetParentFolderName(vmfolder)

vm = Replace(Replace(vmfolder, vmparent, ""),"\","")

bkfile = bkpath & vm & "-" & iso_date(now) & ".zip"

zipfile = inputBox("Now, please enter the full path to the .zip file the script will create:",header,bkfile)

' Quit if cancel

if zipfile = "" then

WScript.Quit

end if

tmpfolder = fso.GetParentFolderName(zipfile) & "\" & vm

way = "i"

' New Section: for working with 2 args

ElseIf args.Count=2 Then 'We are in the automatic mode with 2 Arguments: VM and backup location

vmfile = args(0)

vmfolder = fso.GetParentFolderName(vmfile)

vmparent = fso.GetParentFolderName(vmfolder)

vm = Replace(Replace(vmfolder, vmparent, ""),"\","")

' bkfile = bkpath & vm & "-" & iso_date(now) & ".zip"

zipfile = args(1)

tmpfolder = fso.GetParentFolderName(zipfile)

' Here we should check if the tmpfolder exists: dunno if it will be automatically created...
' If not, it should be created on this place programmatically...

way = "a"

' /New Section

Else

' There is more than one argument provided: write the error message into the application log and bye.
' There is no message box / email here.

errNoVMfile = "Incorrect Input." & VbCrLf & "The directory where the Virtual Machine files" & VbCrLf & "are resided must be provided as argument." & VbCrLf & "If the directory name contains spaces," & VbCrLf & "please add the " & Chr(34) & " sign at the beginning" & VbCrLf & "and at the end of the Virtual Machine's name." & VbCrLf & "The reading of the source code" & VbCrLf & "of the vm-backup.vbs script may help ;)"

wshShell.LogEvent 1, errNoVMfile

WScript.Quit

End If

' Try to connect to server 10 times

connected = False
For tries_srv = 1 To 10
server.Connect cp
If Err.number = 0 Then
connected = True
Exit For
End If
WScript.Sleep 10000
Err.clear
Next

If Not connected Then

'Connection to server couldn't be established; we write something into the application log or/and send a message...

errNoConnectSRV = "The Backup Script for VMware Server couldn't create an appropriate connection." & VbCrLf & "Please check if all of the VMWare Services are up and running." & VbCrLf & "Please keep in mind, you can run this script on the local host only."

wshShell.LogEvent 1, errNoConnectSRV

mailing.Subject = header & ": Critical Error"
mailing.TextBody = errNoConnectSRV
mailing.Configuration.Fields.Update
mailing.Send

if way = "i" Then
crySRV = msgBox(errNoConnectSRV,vbCritical,header)
end if

WScript.Quit

End If


' Connect to the virtual machine. You remember, what the "vmfile" is?

' Try to connect to vm 10 times

connected_m = False
For tries_vm = 1 To 10
thevm.Connect cp, vmfile
If Err.number = 0 Then
connected_m = True
Exit For
End If
WScript.Sleep 1000
Err.clear
Next

If Not connected_m Then

'Connection to vm couldn't be established; we write something into the application log or/and send a message...

errNoConnectVM = "The Backup Script for VMware Server couldn't connect to the virtual machine " & vmfile & "." & VbCrLf & "Please check if the path to .vmx file correct is and if the virtual machine is registered on your server." & VbCrLf & "Please keep in mind, you can run this script on the local host only."

wshShell.LogEvent 1, errNoConnectVM

mailing.Subject = header & ": Critical Error"
mailing.TextBody = errNoConnectVM
mailing.Configuration.Fields.Update
mailing.Send

if way = "i" Then
cryVM = msgBox(errNoConnectVM,vbCritical,header)
end if

WScript.Quit

End If

' Enough with checking
' Get the ExecutionState of the vm to know if it must be started after backup complete

' Const vmExecutionState_Off = 2
' Const vmExecutionState_On = 1
' Const vmExecutionState_Stuck = 4
' Const vmExecutionState_Suspended = 3
' Const vmExecutionState_Unknown = 5

' now we need only 2 states

ps = thevm.ExecutionState

if ps = 1 then

was_on = true ' It must be powered on after backup

elseIf ps = 2 then

was_on = false ' After backup do nothing

else

' If vm stucks, suspended or in unknown state... Who needs such backups? We create some errors.

errState = "The Backup Script for VMware Server couldn't get the correct state of the virtual machine " & vmfile & "." & VbCrLf & "Correct states are on and off only." & VbCrLf & "A vm with pending question, such as new SID after copying or moving, cannot be backed up, too."

wshShell.LogEvent 1, errState

mailing.Subject = header & ": Critical Error"
mailing.TextBody = errState
mailing.Configuration.Fields.Update
mailing.Send

if way = "i" Then
cryVM = msgBox(errState,vbCritical,header)
end if

WScript.Quit

end If

' Heartbeat. It's the approximate number of seconds from the start of VMWare Tools inside the vm.

hb = thevm.Heartbeat

if was_on = true then

if hb < 1 then ' VMWare Tools not installed or cannnot be contacted...

' VM without VMWare Tools can only be backed up if it was off...

errTools = "The Backup Script for VMware Server couldn't contact the VMWare Tools on the virtual machine " & vmfile & "." & VbCrLf & "Therefore it cannot be shut down correctly." & VbCrLf & "Please shut down the vm manually. Afterwards it can be backed up."

wshShell.LogEvent 1, errTools

mailing.Subject = header & ": Critical Error"
mailing.TextBody = errTools
mailing.Configuration.Fields.Update
mailing.Send

if way = "i" Then
cryTools = msgBox(errTools,vbCritical,header)
end if

WScript.Quit

end if

end if

' start/stop
' Const vmPowerOpMode_Hard = 1
' Const vmPowerOpMode_Soft = 2
' Const vmPowerOpMode_TrySoft = 3

' Now stopping...

getoff = thevm.stop(2)

isoff = False

For tries_off = 1 To 10
ps = thevm.ExecutionState
If ps = 2 Then
isoff = True
Exit For
End If
WScript.Sleep 60 * 1000
ps = 0

Next

If Not isoff Then

'The vm couldn't be shut down: very critical...

errNoShutDown = "The Backup Script for VMware Server couldn't shut down the virtual machine " & vmfile & "." & VbCrLf & " in a reasonable time." & VbCrLf & "Please check it's state."

wshShell.LogEvent 1, errNoShutDown

mailing.Subject = header & ": Critical Error"
mailing.TextBody = errNoShutDown
mailing.Configuration.Fields.Update
mailing.Send

if way = "i" Then
cryNoShutDown = msgBox(errNoShutDown,vbCritical,header)
end if

WScript.Quit

end if

' Machine is shut down and can be copied

copyVM = fso.CopyFolder(vmfolder,tmpfolder) 'checked

' Machine copied!

if was_on = true then 'Power on the vm if it was on

geton = thevm.start(2)

' Wait until the heartbeat becomes more than 300

ison = False

For tries_on = 1 To 20
hbs = thevm.Heartbeat
If hbs > 300 Then
ison = True
Exit For
End If
WScript.Sleep 30 * 1000
hbs = 0

Next

If Not ison Then

'The vm couldn't be start up: very critical...

errNoStart = "The Backup Script for VMware Server couldn't power on the virtual machine " & vmfile & "." & VbCrLf & " in a reasonable time. Maybe the machine could not start the VMWare Tools." & VbCrLf & "Please check it's state and / oder configuration."

wshShell.LogEvent 1, errNoStart

mailing.Subject = header & ": Critical Error"
mailing.TextBody = errNoStart
mailing.Configuration.Fields.Update
mailing.Send

if way = "i" Then
cryNoStart = msgBox(errNoStart,vbCritical,header)
end if

WScript.Quit

end if

end if

' Now the vm is up and running. It is copied and ready to be compressed

backup_string = "7za a -tzip " & chr(34) & zipfile & chr(34) & " " & chr(34) & tmpfolder & "\*" & chr(34) & seven_zip_switch

' Now create the archive...

backup_vm = wshshell.Run(backup_string,0,true)

if backup_vm > 0 then

' The zip file wasn't created

errNozip = "The Backup Script for VMware Server couldn't create a zip file." & VbCrLf & "Please check if you have enough disk space on " & tmpfolder & " and run / shedule the backup script again."

wshShell.LogEvent 1, errNozip

mailing.Subject = header & ": Critical Error"
mailing.TextBody = errNozip
mailing.Configuration.Fields.Update
mailing.Send

if way = "i" Then
cryNoZip = msgBox(errNozip,vbCritical,header)
end if

WScript.Quit

end if

' Now delete the temporary backup folder...

deltmp = fso.deleteFolder(tmpfolder) 'should be ok

' And send some messages.

success_message = "The Backup Script for VMware Server backed up the virtual machine " & vmfile & " successfully." & VbCrLf & "Backup is saved as " & zipfile & "."

wshShell.LogEvent 0, success_message

mailing.Subject = header & ": Operation Successfully Completed"
mailing.TextBody = success_message
mailing.Configuration.Fields.Update
mailing.Send

if way = "i" Then
cryS = msgBox(success_message,vbExclamation,header)
end if

WScript.Quit [/code]

Message was edited by:
RDPetruska
Updated Script by Saxa


Found a minor error: the "fso" object is declared twice...

I'm trying this now :-)

Well I tried it in interactive mode and it worked perfectly! This could be a real lifesaver for me, thanks for writing it.

I may have some trouble in command-line mode as my naming convention for disks is:

<servername>_c-drive.vmdk
<servername>_d-drive.vmdk

but I guess I can hack your script to work around this.

Thanks again for writing this.

Martin

One thing I noticed - when the VM came back up and I logged on, I got a "windows previous shutdown was unexpected" dialog. Does the script do a clean guest shutdown?

Naming convention for disks doesn't matter.

Interesting is the naming of your .vmx files

Does the script do a clean guest shutdown?

Sure!

If it was impossible for the script to shut down the VM gracefully, it raises an error - via mail and in the application log - but it doesn't do a brutal power off.

Could you describe what did you see while the script was running, step by step?

Hello,
I used your script! It works great but I think I am missing something.
I am having a problem with the script.
The script shuts down my virtual machine.
and it creates a folder in the backup path.
and it copies the files to the folder.
it then restarts the virtual machine and then instead of zipping the files
it seems to delete the folder.
could you show me what change I need to make to the script.

Thank you very much,

Ken

Hello Ken,

have you read the leading comment?

code
' For the backup jobs it uses the command line version of 7zip: get it on http://7zip.org/download.html.
' You need the "7-Zip Command Line Version". Or, just download the full install - there is also a 64 bit
' version available.
'
' We assume that the 7zip executable is included in your %PATH% variable.
' Most probably you already have a folder with your tools, where you will also save this script.
' We have on each of our servers the folder C:\Program files\myTools created and it is added to %PATH%.
'
[/code]

The 7zip executable 7za.exe couldn't be found in your %PATH%.

Some errors in Application Log?

Yes indeed.
I also downloaded 7zip and installed it.
and I made sure it was in my path.

thanks

What I'm really missing:

there is no "disconnect" method, nor for VmCOM.VmServerCtl neither for VmCOM.VmCtl.

So, the script stays connected to the server and to the vm all the time. I would close both connections after the Line 476 :)

I also downloaded 7zip and installed it.

Have you got the 7za.exe?

Open the command prompt and type in "7za" without quotation marks. What are you getting?

7za doesn't need to be installed, it's a plain executable.

Message was edited by:
saxa

I down loaded the windows 7z442.msi.
but that does not installed 7z.exe.
should i uninstall and install the command line version?

thanks

should i uninstall

No need for it. If you added "C:\Program files\7zip" to path, just copy the 7za.exe into this directory.

Or, just copy it into %WINDIR%\System32...

but that does not installed 7z.exe.

Sure it did. But you need 7za.exe

http://prdownloads.sourceforge.net/sevenzip/7za442.zip?download

Thanks
I will do that now!

That fixed it.
And once again thanks it works great!

OK!

This is awesome. Thanks so much for sharing!

No problem!

I'm still waiting for comments / tips...

Does the script do a clean guest shutdown?

Sure!

If it was impossible for the script to shut down the
VM gracefully, it raises an error - via mail
and in the application log - but it doesn't do a
brutal power off.

Could you describe what did you see while the
script was running, step by step?

I just tried another one and the same thing occurred, after logging on I got the "Unexpected shutdown" message.

I am running the script in interactive mode. I select the .vmx and the backup location. The script runs perfectly with no errors. The vm shuts down, the files are copied, the vm starts, and then the .zip file is made. I get emailed a "success" message, there are no errors. However I get the "unexpected shutdown" when I log onto the vm.

Any thoughts?


Hm... I would think, it's some prog inside the VM that doesn't allow the VM to be shut down.

Please make some tests:

0. Check twice, if the VMware Tools is installed and correctly running on the VM.

1. Try to apply the script to another VM.

2. While the VM is running, press the "Stop" button on the console. Or, select Power -> Shut down Guest. This commands do the same that my script does: it connects to VMware Tools inside the VM and raises the command to shut down. After shut down start the VM once more and see if there is an "unexpected shutdown".

3. Try to shut down the VM using vmware-cmd utility. Start the Command line and run the following command:

code
"C:\Program Files\VMware\VMware Server\vmware-cmd.bat" "D:\Virtual Machines\Virtual Machine 1\vm.vmx" stop

'change the paths according to yours
[/code]

and see if the VM shuts down. If not, reinstall VMware Tools. If yes, see, if you get the "unexpected shutdown".

Hi,

i tries to run the script on a Vista RC1 host with a Windows 2003 R2 guest. I've tried the interactive mode. 7zip is in my path, i've installed VMware tools and can shutdown the guest with the vmware-cmd commandline.

This is teh message i get when running the script: The Backup Script for VMware Server couldn't connect to the virtual machine <path>. Please check if the path to the .vmx file correct is and if the virtual machine is registeredon your server.

I'm running the script on the localhost.
I'm have to right path to the .vmx file.
But i don't know if i have registered the virtual machine???

Regards,
Patrick

run the script on a Vista RC1

I didn't test my script on Vista: it's a non-supported host. I even didn't test it on Windows 2000 Pro, because of the same reason. On WinXP it works perfectly.

You better consider to use W3K as host, especially if you speak of production...

7zip is in my path

Please check twice taht you have the 7za executable. The 7z one will not do the work.

But i don't know if i have registered the virtual machine???

If you see / can use the VM in the console, it's already registered.

The Backup Script for VMware Server couldn't connect to the virtual machine <path>

Please publish the <path>

This is the path to my VMware machine "C:\Virtual Machines\Windows Server 2003 R2".... The backup path is: "C:\backup".

I will try the same on a W2K3 host. offcourse it is no production environment, just my notebook ;-)

This is the path to my VMware machine "C:\Virtual Machines\Windows Server 2003 R2"....

Sure. Please publish the full path.

C:\Virtual Machines\Windows Server 2003 R2\Windows Server 2003 R2.vmx

The path is correct...

Please try the script on W2K3 host. I think, the WSH on Vista interprets the paths on other way; say the "fso" object is different...

Great work on this! Thanks for sharing. It seems to work great interactively and I have my first scheduled command line job set for this weekend. I have been looking for a tool like this.

Tried Windows 2003 as host, this works great thanks.

Glad you like it!

OK, I will work on the code working on Vista as soon as the main app will run on it.

Good news, the script also works on a Vista Host with a Windows 2003 guest. I just made a very stupid typo before. Thanks for helping me out, the script works beautiful.

Are you also interested in feature requests?

Patrick

Are you also interested in feature requests?

Sure!

What about a scripted snapshot. Maybe it is possible to snapshot a running machine from time to time eacht day.

A feature where we can choose the amounts of backup ZIP files would also be nice. If it is possible to limit the amount of ZIP files to fe. 7 the ZIPs are overwritten each week.

Patrick

What about a scripted snapshot.

1. Sorry, I never use snapshots on the VMware Server, only on Workstation, so I wouldn't implement it.

2. The VMCom doesn't support it.

If it is possible to limit the amount of ZIP files to fe. 7 the ZIPs are overwritten each week.

I would use another script for it, which deletes files older then [date]. I think, there are some ready-to-use on the net, but I could write one, too.

Message was edited by: saxa (Grammar ;))

code

'This script deletes files older than 7 days in folder Y:\some folder\some folder more\my files

Set fso = CreateObject("Scripting.FileSystemObject")

Set fldr = fso.GetFolder("Y:\some folder\some folder more\my files")
Set fc = fldr.Files
For Each fl in fc
If DateDiff("d", fl.DateLastModified, Now) > 7 Then fl.Delete
Next

[/code]

Hey, thanks allot. With these scripts this can be a simple but effective backup sollution for very small company's.

Regards, Patrick

You should be very carefully while using the last script: it deletes all files older than 7 days. It means, if you have only one zip file of some VM and it's older than that, it will be also deleted.

Reading around forums it seems that nobody use the VMWare ability to reduce the vmdk file size, am I the only one ?
I mean that I use the vmware-vdiskmanager utility in making cold backups (options "-r" mixed with "-t 0"). This is surely slower than a direct copy but it reduces the vmdk file size and would only copy used bytes.

it reduces the vmdk file size

On virtual servers we don't use the growable vmdk files, because they don't perform so good as preallocated do.

We use preallocated ones.

The target of my script is a quick backup with minimal interruption of the running VM. IMHO nothing can be quicker as a plain copying of files.

I use the preallocated type too, but I use a conversion to growable type for backuping
The interruption of VM is not a problem for my Vmware server environment : I have nothing on production

I use a conversion to growable type for backuping

I see. But zip/7zip compresses better.

codethe resulting file has the size of 3.6 GB: compare it to 52 GB uncompressed[/code]

Great script, exactly what I have been looking for.

Very easy to setup, just change a few variables, and I can now backup my 11 guests.

Now I just need to be able to change backup-destination depending on the day, so i can split the backup to two different locations.

For my purpose, I had to change the script, so it did not require any specific naming-convention, but that was easy, as your original script is well documented.

Thanks for this great inspiration.

Why not share this change?

I will also modify my script ASAP, so it also could be run such as

code
vm-backup.vbs "X:\Full Path To vmx File\My vmx file.vmx" "Y:\Full Path To Anyhow Named zip File\bla bla\Any name.zip"
[/code]

original script is well documented.

I couldn't create it without it :)

I'm still searching for a comparable script for Linux hosts... Could somebody create one?

I will be looking forward to this change - it will make it so much easier to split the backup to different locations.

If you need a beta-tester, let me know.

If you need a beta-tester, let me know.

You can begin ;)

The script is updated now; this change is implemented (maybe not as good as it should be).

Comments to betascript:

Just tested in on a windows xp guest i had running, local copy:

It took around 3 minutes to shut it down, the copy took 2 minutes (3 GB) and the zip took 25 minutes, compressed from 3 GB to 1,5 GB.

My second test on same xp guest, copy to network:
It took around 1 minute to shut it down, the copy took 3 minutes (3 GB) and the zip took 45 minutes, same compression from 3 GB to 1,5 GB.

On both occasions, it seems, that the zip-file is created in backup-directory I specified, but the delete after verifying the zip-file was created, is not working - the vmdk-files are still there.

It could be nice if you could both specify the copy-location and the zip-location, as there is alot of overhead when copying 50 GB. over the network, then reading it all again, to create a 7zip-file over the network again.

I also saw that if for any reason, a user is logged in, and is running a program, it will not shut down the server, merely asking if you want to save changes, and waits forever.

The script has alot of timeouts (which is good) - but what about some progress indicators, so we know where in the script we are ?
Example: wscript.echo "Currently waiting for " vm " to shut down" etc.

Addons: Duration of script, included in email report.

Please keep developing


Hello,

It took around 3 minutes to shut it down, the copy took 2 minutes (3 GB) and the zip took 25 minutes, compressed from 3 GB to 1,5 GB.

It's OK, IMHO.

My second test on same xp guest, copy to network: It took around 1 minute to shut it down, the copy took 3 minutes (3 GB) and the zip took 45 minutes, same compression from 3 GB to 1,5 GB.

Should be OK, too.

the vmdk-files are still there.

Perfect! The first bug ;)

there is alot of overhead when copying 50 GB. over the network, then reading it all again, to create a 7zip-file over the network again.

Agree. Could be done.

I also saw that if for any reason, a user is logged in, and is running a program, it will not shut down the server, merely asking if you want to save changes, and waits forever.

Here is nothing to do. I'm just using Vmware Tools for shutdown, which can or can't shutdown the VM...

The script has alot of timeouts

The script will have even more timeouts: there are some reasons for it.

what about some progress indicators, so we know where in the script we are ? Example: wscript.echo "Currently waiting for " vm " to shut down" etc.

Normal use of the script is for sheduled task, so forget the "echoes" :)
I can easily add some messages, but they will inform the user only on:

* End of zipping

AFAIK 7zip has some returns on the end of it's operation only, so it wouldn't be possible to show the zipping progress.

Honestly: do you really need it?

Addons: Duration of script, included in email report.

Wonderful idea!

Please keep developing

I will :)

Maybe it is possible to copy the files to antoher machine. After that let the other machine ZIP the files. So the VM is quicker available with all resources. It is possible to start a script from another machine on a Windows network.

Patrick

yes it is possible, utlizing a great great tool from sysinternals called psexec.

It is not that easy to script, but is indeed possible.

I'm satisfied, when I can shutdown a vm, copy the files, start the vm again, and start another script on my other backup-server which will compress it and delete it.

start another script on my other backup-server which will compress it and delete it

It's too complicated. How will you arrange these scripts to communicate with each other?
Keep it simple ;)

This is not complicated. As stated by Jungsberg the little sysinternals (now Microsoft) can do this: http://www.sysinternals.com/FileAndDiskUtilities.html see PsTools.

Maybe you can make the zipping an OPTION. So we can choose to use it or not. If i not use it i can run a script after yours that triggers a script on another sevrver via psexec. That way i can ZIP the backup at every convience time?!

Patrick

Thanks, I know what pstools are ;)

Will implement it, as an option.

On both occasions, it seems, that the zip-file is created in backup-directory I specified, but the delete after verifying the zip-file was created, is not working - the vmdk-files are still there.

Quick patch:

Please find

code
tmpfolder = fso.GetParentFolderName(zipfile)
[/code]
and replace by

code
tmpfolder = fso.GetParentFolderName(zipfile) & "\" & vm
[/code]

It could be nice if you could both specify the copy-location and the zip-location, as there is alot of overhead when copying 50 GB. over the network, then reading it all again, to create a 7zip-file over the network again.

Quick addition:

1. Find

code
ElseIf args.Count=2 Then 'We are in the automatic mode with 2 Arguments: VM and backup location
[/code]
and replace with

code
ElseIf args.Count=3 Then 'We are in the automatic mode with 3 Arguments: VM, backup and temp location
[/code]

2. Find

code
tmpfolder = fso.GetParentFolderName(zipfile) & "\" & vm

' Here we should check if the tmpfolder exists: dunno if it will be automatically created...
[/code]

and replace with

code
tmpfolder = args(2) & "\" & vm

' Here we should check if the tmpfolder exists: dunno if it will be automatically created...
[/code]

Now you must call the script as following:

vm-backup.vbs "X:\Some Folder\MyVM.vmx" "Y:\backup\MyZipFile.zip" "Z:\temporary location"

Message was edited by:
saxa


I thought about using psexec for a long time and I will not use it.

There are too many paths you have to program or to parse: file server's network path; local paths on the file server; local paths on the VMware server... You wouldn't want to work with the script any more...

I will add a possibility to apply the script to remote VMware servers instead. It can be started on the file server, which also will compress. It's nearly the same.

Maybe you can make the zipping an OPTION. So we can choose to use it or not. If i not use it i can run a script after yours that triggers a script on another sevrver via psexec.

It is already an option. Just delete / comment the code which produces zips... :)

Whohoo, thank you very much.

I have tested your changes, and I am very pleased with the results.

I can now backup my VM's weekly, with minimal downtime, thanks to your script.

Again, this is just what I needed and I am very happy.

Thanks.

Hello, I'm happy you like it!

Are you interested in a remote execution of the script, I mean, applying the script to remote host?

I think, on this way you can also backup the VMs running on Linux hosts...

I'm developing... :)

Yes, I would be interested in that.

I have a dedicated backup-machine, which would be running it.

Hi saxa,

Fantastic script!

It would be great to backup all VMs from one central Windows server including the Linux hosts.

Hence, I am looking forward to see your latest script.

Bye the way, where would I get the latest and greatest version?

Thanks

Hello York,

after I'm ready with developing (unfortunately it will take some more time as expected) I will publish it right here.

It would be great to backup all VMs from one central Windows server including the Linux hosts.

That's what I'm going to do.

Here is the output mail of the new script version:

code
The Backup Script for VMware Server backed up the virtual machine E:\vm2\mx\vm.vmx successfully.
Backup is saved as F:\backups\mx-2006-11-15-002115.zip.

The VM was 8 minutes offline.

The compress operation took 18 minutes.

Total execution time was 26 minutes.

Operation begin was 2006-11-15-002117.

Operation end was 2006-11-15-004716.

[/code]

Looks good? ;)

And, we can handle remote hosts, too.

Attention: some things are changed!

1. The easiest way to execute the script is

code
vm-backup.vbs "D:\Virtual Machines\Machine 1\MyVM.vmx"
[/code]

The older variant vm-backup.vbs "Machine 1" will not work. You are free to host your machines everywhere.

2. We need the full install of 7-zip now. The script will check, if it's installed and cry, if it isn't.

3. Remote execution...

So, here we go:

code
' Copyleft saxa aka Alexander Kaufmann, 2006

' Written just for fun; total Open Source.
' Use it at your own risk.

' The script uses the VmCOM API for the virtual machine operations.

' The virtual machine *must* have the VMware Tools installed, in order to
' perform the shutdown and heartbeat operations correctly.

' DON'T APPLY THIS SCRIPT ON RUNNING VIRTUAL MACHINES
' WHICH DON'T HAVE THE VMWARE TOOLS INSTALLED.

' The script will work on Windows 2000 SP4 and newer.
' It was also successfully tested on Vista.

' Plese keep in mind the strangeness of the script execution
' on 64bit Windows: there is no VmCOM 64bit, so you have to run it
' in 32bit context; see your Windows Help for details.

' The script can be applied to a local host or to remote host: see the
' remote_server variable.
' The script *can* backup to the network share,
' if you have the appropriate permissions to write on it.

' For the backup jobs the script uses the command line version of 7zip.
' Get it on http://7zip.org/download.html.
' Just download the full install - there is also a 64 bit version available.

' The script will find the 7zip automatically.
' If it's not installed, the script will let you know. ;)

' Most probably you already have a folder with your tools,
' where you will also save this script. We have on each of our servers
' the folder C:\Program files\myTools created and it is added to %PATH%.

' Please see Windows Help on how to add a folder to %PATH%.

' Here I go again (c) ;))
'
' We assume that all of your virtual machines are located
' in the appropriate subdirectories.
' Here is a sample of correct directory layout we can work with:

' D:\Virtual Machines\
' Virtual Machine 1\
' vm.vmx
' hdd1.vmdk
' hdd1-flat.vmdk
' hdd2.vmdk
' hdd2-flat.vmdk
' other_file.ext
' Virtual Machine 2\
' Weird OS.vmx
' disks\
' some weird disk 1.vmdk
' some weird diskette.flp

' As you can see, subdirectories are OK. It's only important
' that your .vmx file is placed on the same level as or higher than
' the VM files we need to backup.

' The subdirectory where the virtual machine is located is very important
' for this script: it's the virtual machine's identifier.
' It will become the part of the name of the zip file.

' In our sample these are "Virtual Machine 1"
' and "Virtual Machine 2" respectively.

' You will start the script as follows:

' vm-backup.vbs "D:\Virtual Machines\Virtual Machine 1\vm.vmx"

' or

' vm-backup.vbs "D:\Virtual Machines\Virtual Machine 2\Weird OS.vmx"

' to backup the Virtual Machine 1 or Virtual Machine 2.

' If you want to use the script in a sheduled task,
' please use the following command line:

' wscript.exe vm-backup.vbs "D:\vm\Virtual Machine 2\Weird OS.vmx"

' to backup the "Virtual Machine 2".

' The script will do the following:

' The VMware Tools inside the virtual machine receives the command
' to shut down the operating system.

' The script waits 30 seconds and checks the state of the virtual machine.
' If the vm still runs, the script waits 30 seconds more and so on.
' As soon as the vm is off, the script creates a copy of the vm's folder
' on the backup location (see the "bkpath" variable and change it
' if you would like to; UNC paths are accepted).

' For remote executing: this path is relative to the machine
' on which the script is executed, not to the VMware host.

' If the vm couldn't be shut down, the mail is sent to the admin,
' the error is written to the Windows application log.
'
' After the copying is done, the vm receives the command to start,
' if it was running before the operation has begun.

' 30 seconds later, and then every 30 seconds, the script checks
' the heatbeat of the vm.

' As soon as the vm at 300 or more units of heartbeat,
' the script starts to create a compressed archive
' from a previously copied vm directory.

' At that point of time is the vm already up and running.

' A .zip archive will be named as: YYYY-MM-DD-HHMMSS-Virtual Machine 1.zip

' The creation of the .zip file takes it's time:
' on Pentium 4 (with Hyperthreading, single core) 2.8 GHz machine
' with 3 GB RAM is the duration of compress operation on a virtual machine
' having 2 virtual HDDs at 16 and 36 GB was about 2 hours.
' Though it is worth the effort: the resulting file has the size of 3.6 GB:
' compare it to 52 GB uncompressed ;).

' So, after the .zip file is ready, the script checks if there were
' any errors produced by 7zip. If there are some, the Windows Application log
' is misused for the registration of them. If not, then we can safely delete
' the copy of the vm used as a source for compression and create the record
' of successful backup operation in the Application log. :P

' The interactive mode (if you start the script without any parameters)
' does the same; you will name your zip file manually.

' It's also possible to run a script as following
' (quite interesting for "scripted scripting"):

' vm-backup.vbs "X:\Full Path To vmx File\My vmx file.vmx" _
' "Y:\Full Path To Some zip File\bla\Any name.zip"

' The script will backup the directory "X:\Full Path To vmx File\"
' including all subdirectories.

' Careful: the script will *not* create the directory
' "Y:\Full Path To Some Folder\bla\"

vmpath = "D:\Virtual Machines\" 'relative to VMware host

' Please don't forget the ending backslash!

' bkpath -> Destination directory; here are temporary backups created,
' and here you will find your .zip files.
' The user who runs the script must have the write permissions
' on directory / network share.

bkpath = "E:\backups\" 'relative to the machine running script

' In the variable seven_zip_switch you can provide
' additional switches for the command line of 7zip.

' The most thinkfully switch is " -v4g" (don't forget the leading space!).
' It causes the splitting of your archive into volumes at 4 GB.
' Please read the 7zip's manual about the -v switch.

seven_zip_switch = ""

adminmail = "mail@domain.com" 'Here you'll receive mail messages.

mailfrom = "info@domain.com" 'The sender of mail messages.

smtp = "smtp.domain.com"

' Your SMTP server must be able to relay the mails
' for your mail address. IP address is also OK.

' Set the following variable to "true" if you are intendend
' to apply the script to remote server

remote_server = false

' If remote_server is true, you must define the following variables

remote_host = "192.168.0.101" 'IP address or host name
'remote_port = "902" '902 is standard; uncomment if it's different
remote_user = "root" 'User on the remote server who may run the VMs
remote_pass = "password" 'User's password

' So, here is the most important thing for remote execution. You have to share
' your Virtual Machines directory on the host. The user who runs the script
' (not the remote_user) must have the read permissions on that share.
' For Linux users: install and configure Samba...
' For Windows users: hidden shares?!

remote_share = "\\server\share\Virtual Machines"

' Path is relative to the machine running script.
' It's not the same as vmpath: it must be a network resource.
' Underneath are your VM folders.

On Error Resume Next

' Common definitions...

Set wshShell = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
Set cp = CreateObject("VmCOM.VmConnectParams")
Set server = CreateObject("VmCOM.VmServerCtl")
Set thevm = CreateObject("VmCOM.VmCtl")
Set wshNet = CreateObject("WScript.Network")
Set mailing = CreateObject("CDO.Message")

mailing.From = mailfrom
mailing.To = adminmail
mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = smtp
mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
header = "Backup Script for VMware Virtual Machines" 'Just the title for message boxes...

Function iso_date(byval dt)

' The function does nothing interesting...

dim y: y=year(dt)
dim m: m=month(dt)
dim d: d=day(dt)
dim h: h=hour(dt)
dim n: n=minute(dt)
dim s: s=second(dt)

if m < 10 then m="0" & m
if d < 10 then d="0" & d
if h < 10 then h="0" & h
if n < 10 then n="0" & m
if s < 10 then s="0" & s

iso_date = y & "-" & m & "-" & d & "-" & h & n & s

end Function

' Check if 7zip is installed

seven_zip_reg = wshShell.RegRead("HKLM\SOFTWARE\7-Zip\Path")

If Err.number 0 then

errNoSevenZip = "The Backup Script for VMware Server couldn't find the 7-zip Application installed on your system." & VbCrLf & "Please visit 7zip.org to get it."

wshShell.LogEvent 1, errNoSevenZip

mailing.Subject = header & ": Install 7-zip"
mailing.TextBody = errNoSevenZip
mailing.Configuration.Fields.Update
mailing.Send
If args.Count=0 Then
crySevenZip = msgBox(errNoSevenZip,vbCritical,header)
End If

WScript.Quit

end if

' Adding the connection info...

If remote_server = true Then

cp.hostname = remote_host
cp.username = remote_user
cp.password = remote_pass
cp.port = remote_port

End If

' Here we are getting the name of the VM delivered by the script argument;
' it must one or two. If there are two, it means, user want to define the VM
' and backup file manually.
' If there are more than two, it's an incorrect call.

Set args = WScript.Arguments

If args.Count=1 Then

'We are in the mode with predefined vm by parameter, way = "a(utomatic)"

vmfile = args(0)

vmfolder = fso.GetParentFolderName(vmfile)

vmparent = fso.GetParentFolderName(vmfolder)

vm = Replace(Replace(vmfolder, vmparent, ""),"\","")

zipfile = bkpath & vm & "-" & iso_date(now) & ".zip"

tmpfolder = fso.GetParentFolderName(zipfile) & "\" & vm

way = "a"

ElseIf args.Count=0 Then

'We are in the interactive mode, way = "i(nteractive)"

vmfile = inputBox("Please enter the full path to the .vmx file of the virtual machine you want to backup:",header,vmpath)

'Quit if cancel

if vmfile = "" then

WScript.Quit

end if

vmfolder = fso.GetParentFolderName(vmfile)

vmparent = fso.GetParentFolderName(vmfolder)

vm = Replace(Replace(vmfolder, vmparent, ""),"\","")

bkfile = bkpath & vm & "-" & iso_date(now) & ".zip"

zipfile = inputBox("Now, please enter the full path to the .zip file the script will create:",header,bkfile)

'Quit if cancel

if zipfile = "" then

WScript.Quit

end if

tmpfolder = fso.GetParentFolderName(zipfile) & "\" & vm

way = "i"

ElseIf args.Count=2 Then

'We are in the automatic mode with 2 Arguments: VM and backup location

vmfile = args(0)

vmfolder = fso.GetParentFolderName(vmfile)

vmparent = fso.GetParentFolderName(vmfolder)

vm = Replace(Replace(vmfolder, vmparent, ""),"\","")

zipfile = args(1)

tmpfolder = fso.GetParentFolderName(zipfile) & "\" & vm

'Here we should check if the tmpfolder exists: dunno if it will be
'automatically created... If not, it should be created
'on this place programmatically...

way = "a"

Else

' There are more than two arguments provided: write the error message
' into the application log and bye.
' There is no message box / email here.

errNoVMfile = "Incorrect Input." & VbCrLf & "The directory where the Virtual Machine files" & VbCrLf & "are resided must be provided as argument." & VbCrLf & "If the directory name contains spaces," & VbCrLf & "please add the " & Chr(34) & " sign at the beginning" & VbCrLf & "and at the end of the Virtual Machine's name." & VbCrLf & "The reading of the source code" & VbCrLf & "of the vm-backup.vbs script may help ;)"

wshShell.LogEvent 1, errNoVMfile

WScript.Quit

End If

' Try to connect to server 10 times

connected = False
For tries_srv = 1 To 10
server.Connect cp
If Err.number = 0 Then
connected = True
Exit For
End If
WScript.Sleep 10000
Err.clear
Next

If Not connected Then

'Connection to server couldn't be established; we write something into the application log or/and send a message...

errNoConnectSRV = "The Backup Script for VMware Server couldn't create an appropriate connection." & VbCrLf & "Please check if all of the VMWare Services are up and running." & VbCrLf & "Please keep in mind, you can run this script on the local host only."

wshShell.LogEvent 1, errNoConnectSRV

mailing.Subject = header & ": Critical Error"
mailing.TextBody = errNoConnectSRV
mailing.Configuration.Fields.Update
mailing.Send

if way = "i" Then
crySRV = msgBox(errNoConnectSRV,vbCritical,header)
end if

WScript.Quit

End If


' Connect to the virtual machine. You remember, what the "vmfile" is?

' Try to connect to vm 10 times

connected_m = False
For tries_vm = 1 To 10
thevm.Connect cp, vmfile
If Err.number = 0 Then
connected_m = True
Exit For
End If
WScript.Sleep 1000
Err.clear
Next

If Not connected_m Then

'Connection to vm couldn't be established; we write something into the application log or/and send a message...

errNoConnectVM = "The Backup Script for VMware Server couldn't connect to the virtual machine " & vmfile & "." & VbCrLf & "Please check if the path to .vmx file correct is and if the virtual machine is registered on your server." & VbCrLf & "Please keep in mind, you can run this script on the local host only."

wshShell.LogEvent 1, errNoConnectVM

mailing.Subject = header & ": Critical Error"
mailing.TextBody = errNoConnectVM
mailing.Configuration.Fields.Update
mailing.Send

if way = "i" Then
cryVM = msgBox(errNoConnectVM,vbCritical,header)
end if

WScript.Quit

End If

' Enough with checking :)

' Create the checkpoint: operation begin

checkpoint_begin = now

' Get the ExecutionState of the vm to know if it must be started after backup complete

' Const vmExecutionState_Off = 2
' Const vmExecutionState_On = 1
' Const vmExecutionState_Stuck = 4
' Const vmExecutionState_Suspended = 3
' Const vmExecutionState_Unknown = 5

' now we need only 2 states

ps = thevm.ExecutionState

if ps = 1 then

was_on = true ' It must be powered on after backup

elseIf ps = 2 then

was_on = false ' After backup do nothing

else

' If vm stucks, suspended or in unknown state... Who needs such backups? We create some errors.

errState = "The Backup Script for VMware Server couldn't get the correct state of the virtual machine " & vmfile & "." & VbCrLf & "Correct states are on and off only." & VbCrLf & "A vm with pending question, such as new SID after copying or moving, cannot be backed up, too."

wshShell.LogEvent 1, errState

mailing.Subject = header & ": Critical Error"
mailing.TextBody = errState
mailing.Configuration.Fields.Update
mailing.Send

if way = "i" Then
cryVM = msgBox(errState,vbCritical,header)
end if

WScript.Quit

end If

' Heartbeat. It's the approximate number of seconds from the start of VMWare Tools inside the vm.

hb = thevm.Heartbeat

if was_on = true then

if hb < 1 then ' VMWare Tools not installed or cannnot be contacted...

' VM without VMWare Tools can only be backed up if it was off...

errTools = "The Backup Script for VMware Server couldn't contact the VMWare Tools on the virtual machine " & vmfile & "." & VbCrLf & "Therefore it cannot be shut down correctly." & VbCrLf & "Please shut down the vm manually. Afterwards it can be backed up."

wshShell.LogEvent 1, errTools

mailing.Subject = header & ": Critical Error"
mailing.TextBody = errTools
mailing.Configuration.Fields.Update
mailing.Send

if way = "i" Then
cryTools = msgBox(errTools,vbCritical,header)
end if

WScript.Quit

end if

end if

' start/stop
' Const vmPowerOpMode_Hard = 1
' Const vmPowerOpMode_Soft = 2
' Const vmPowerOpMode_TrySoft = 3

' Now stopping...

getoff = thevm.stop(2)

isoff = False

For tries_off = 1 To 10
ps = thevm.ExecutionState
If ps = 2 Then
isoff = True
Exit For
End If
WScript.Sleep 60 * 1000
ps = 0

Next

If Not isoff Then

'The vm couldn't be shut down: very critical...

errNoShutDown = "The Backup Script for VMware Server couldn't shut down the virtual machine " & vmfile & "." & VbCrLf & " in a reasonable time." & VbCrLf & "Please check it's state."

wshShell.LogEvent 1, errNoShutDown

mailing.Subject = header & ": Critical Error"
mailing.TextBody = errNoShutDown
mailing.Configuration.Fields.Update
mailing.Send

if way = "i" Then
cryNoShutDown = msgBox(errNoShutDown,vbCritical,header)
end if

WScript.Quit

end if

' Machine is shut down and can be copied

If remote_server = true Then

vmfolder = remote_share & "\" & vm

End If

copyVM = fso.CopyFolder(vmfolder,tmpfolder) 'checked

' Machine copied!

if was_on = true then 'Power on the vm if it was on

geton = thevm.start(2)

' Wait until the heartbeat becomes more than 300

ison = False

For tries_on = 1 To 20
hbs = thevm.Heartbeat
If hbs > 300 Then
ison = True
Exit For
End If
WScript.Sleep 30 * 1000
hbs = 0

Next

If Not ison Then

'The vm couldn't be start up: very critical...

errNoStart = "The Backup Script for VMware Server couldn't power on the virtual machine " & vmfile & "." & VbCrLf & " in a reasonable time. Maybe the machine could not start the VMWare Tools." & VbCrLf & "Please check it's state and / oder configuration."

wshShell.LogEvent 1, errNoStart

mailing.Subject = header & ": Critical Error"
mailing.TextBody = errNoStart
mailing.Configuration.Fields.Update
mailing.Send

if way = "i" Then
cryNoStart = msgBox(errNoStart,vbCritical,header)
end if

WScript.Quit

end if

end if

' Now the vm is up and running. It is copied and ready to be compressed.

' Create the checkpoint: the VM is running.

checkpoint_started = now

' It's time to destroy the VMware objects and make a pause

WScript.Sleep 30 * 1000
Set thevm = Nothing
WScript.Sleep 5 * 1000
Set server = Nothing
WScript.Sleep 5 * 1000
Set cp = Nothing
WScript.Sleep 30 * 1000

backup_string = chr(34) & seven_zip_reg & "\7z.exe" & chr(34) & " a -tzip " & chr(34) & zipfile & chr(34) & " " & chr(34) & tmpfolder & "\*" & chr(34) & seven_zip_switch

' Now create the archive...

backup_vm = wshshell.Run(backup_string,0,true)

if backup_vm > 0 then

' The zip file wasn't created

errNozip = "The Backup Script for VMware Server couldn't create a zip file." & VbCrLf & "Please check if you have enough disk space on " & tmpfolder & " and run / shedule the backup script again."

wshShell.LogEvent 1, errNozip

mailing.Subject = header & ": Critical Error"
mailing.TextBody = errNozip
mailing.Configuration.Fields.Update
mailing.Send

if way = "i" Then
cryNoZip = msgBox(errNozip,vbCritical,header)
end if

WScript.Quit

end if

' Now delete the temporary backup folder...

deltmp = fso.deleteFolder(tmpfolder) 'should be ok

' Pause...

WScript.Sleep 5 * 1000

' Create the checkpoint: ready...

checkpoint_ready = now

' Calculate time used...

time_off = DateDiff("n",checkpoint_begin,checkpoint_started)
time_cmp = DateDiff("n",checkpoint_started,checkpoint_ready)
time_sum = time_off + time_cmp

' And send some messages.

success_message = "The Backup Script for VMware Server backed up the virtual machine " & vmfile & " successfully." & VbCrLf & "Backup is saved as " & zipfile & "."

If was_on = true then

success_message = success_message & VbCrLf & VbCrLf & "The VM was " & time_off & " minutes offline."

End If

success_message = success_message & VbCrLf & VbCrLf & "The compress operation took " & time_cmp & " minutes."

success_message = success_message & VbCrLf & VbCrLf & "Total execution time was " & time_sum & " minutes."

success_message = success_message & VbCrLf & VbCrLf & "Operation begin was " & iso_date(checkpoint_begin) & "."

success_message = success_message & VbCrLf & VbCrLf & "Operation end was " & iso_date(checkpoint_ready) & "."

wshShell.LogEvent 0, success_message

mailing.Subject = header & ": Backup Operation Successfully Completed"
mailing.TextBody = success_message
mailing.Configuration.Fields.Update
mailing.Send

if way = "i" Then
cryS = msgBox(success_message,vbExclamation,header)
end if

WScript.Quit
[/code]


This looks absolutely great !!

Will try it tonight, and let you know..

TNX.
This work ok.

First I must say that this script ROCKS!

One question though...I'm wondering what purpose this line serves in the new version.

vmpath = "D:\Virtual Machines\" 'relative to VMware host

I've searched for vmpath in the script and it's only used in a comment and in interactive mode when setting the value for vmfile. Should this line even be there any more?

OK, I lied, another question. In this line I assume the the extra "vm" a typo?

' wscript.exe vm-backup.vbs "D:\vm\Virtual Machine 2\Weird OS.vmx"


So I tried the remote execution and came across an issue. Most likely someone a bit smarter would not have been in this situation.

I kept getting a message that 7-zip was not installed, even though it was. I checked the code and it appears it checks the registry for the path to 7-zip, then if an error exists assume 7-zip was not found. The issue "for me at least" is that an error was raised before the check for 7-zip. It's just that the code assumes the error must be 7-zip is missing.

I tracked down my real error to not having the VmCOM API's installed. I just wanted to post here in case anyone else might come across the same thing. The API's can be downloaded here:

http://www.vmware.com/download/sdk/api.html

Really minor but the following comment does not match the code:

' A .zip archive will be named as: YYYY-MM-DD-HHMMSS-Virtual Machine 1.zip

bkfile = bkpath & vm & "-" & iso_date(now) & ".zip"

I tracked down my real error to not having the VmCOM API's installed.

That's correct. I should also check it...

I'm not a programmer, I'm just a lazy admin ;)

the following comment does not match the code

Feel free to correct it :)

sorry im a newb at all of this scripting stuff and i tried this script out and ran into some errors.

I have a base machine running W2k3 Standard 64Bit. I have 2 Virtual machines but am only testing this on one of them. The First virtual machine is stordd in D:\Vmware\Windos Server 2003 Small Business.vmx

I installed 7-Zip (the 64 bit version) but when i run the script it gives me an error that it cant find the 7-zip application insatlled. I checked the path in regedit and its there under HKEYLM\Softare\7-zip\Path (path = c:\program ile\7-zip)
so to get around this first problem I commented out the part where it checks for 7-Zip.

Once I comment it out I get another error after 60 seconds or so. The error that shws up in my event viewer is "The backup script for Vmware Server couldnt create an appropriate connection. Please check if all of the Vmware Services are up and running. please keep in mind, you can run this script on the local host only"

I checked services and all VMware Services are running.

In the orginal script the only things I changed was:

vmpath = "D:\Vmware\" (where my virtual server is)

bkpath = "F:\backups\" (the drive i will like to save to)

I also changed the mail settings but thats all...
I saw somewhere down the script a vmfile = inputbox so i did not enter in my vmx location since i thought it would ask since its an input box? same goes for the zipfile = string....

am I supposed to make more changes to the script file? if so what else am i supposed to change?

i am running the script from a batch file that has the following entry: vm-backup.vbs "D:\Vmware\Windows Server 2003 Small Business.vmx"

what am I doing wrong? How can i fix this? im sorry since im a newb at this stuff i really dont know what to check/fix

any help will be apperciated!

thx in advance!

On 64bit OS the script must be executed in 32bit context.

code
' Plese keep in mind the strangeness of the script execution
' on 64bit Windows: there is no VmCOM 64bit, so you have to run it
' in 32bit context; see your Windows Help for details.
[/code]

It means, you can't run the script directly; you should rather run it as

code
%WINDIR%\Wowexec\wscript.exe vm-backup.vbs
[/code]

I'm not quite sure about the path, it's similar. Unfortunately, I haven't any 64bit installs here, so please check the path yourself.

Message was edited by:
saxa

anyone get this working on x64? If so how?

Saxa: do i need to change anything else in the script?

I ran it from the directory that Saxa was talking about
c:\windows\syswow64 but still no luck... :s

Message was edited by:
Louch


I ran it from the directory that Saxa was talking about
c:\windows\syswow64 but still no luck... :s

Please publish the command line you used.

if you get an error that 7zip is not installed and you have checked the registry entry that the script is looking at and there is a value then you are getting an erro before this check in the script. The check for 7zip assumes no errors have already occured. As such it also captures previous errors.

Luckily there are not many lines of code before this. Just insert a bunch of messageboxes at various places above this part of the script.

"msgbox err.number"

If the result is NOT zero you have an error somewhere before the messagebox. It should be fairly easy to track down what line of code is causing it. Fixing it might be a different issue though.

Based on the other posts concerning the 64bit stuff i'm suspecting all three of these (but then, what do i know :)
Set cp = CreateObject("VmCOM.VmConnectParams")
Set server = CreateObject("VmCOM.VmServerCtl")
Set thevm = CreateObject("VmCOM.VmCtl")

ok well it kind of worked but the end result was an empty folder...

i ran the script from C:\Windows\SysWoW64\wscript.exe vm-backup.vbs
(i had the 7-zip part commented out since it would not picked that up as being installed)

The input box asked me where my vmx file was so i gave it the full path
(in this case d:\Vmware\Windows 2000 Small Business.vmx) and than it
asked me for the backup zip path (it already had in F:\backups\<file name it creates.zip> so I clicked ok.

It shutdown the vmware sbs and it started the copy. (i opened the F:\backups\ folder to see if it made a directory and it did) it finished
copying over the file. (Things were all great at this point!!)

A couple of minutes later it popped up with a message saying:
"The backup script for vmware server backed up the virtual machine <path> successfully. Backup Saved as F:\backups\vmware-2006-11-27-154301.zip.
The VM was 11 minutes offline
The compress operation took 2 minutes
total exeuctuation time was 13 minutes
operation begin was 2006-11-27-154311
operation end was 2006-11-27-155603

BUT
when I go check the F:\backups\ direcotry its EMPTY!!!!
so I know the script is supposed to delete the orginal files after it zips them but there was NO ZIP file there....

Does anyone know why there is no zip file there even though I got the successful popup window at the end? could it have somthing to do with me commenting out the 7-zip check part in the script since it kept telling me 7-zip is not installed even though it is?

does anyone know how to fix this?

thx!


The command used to zip the files depends on the registry entry to locate the 7zip. Since you commented out the registry check for 7zip it can't find it and thereforedoes not do the zip operation.

ZipCommand = chr(34) & seven_zip_reg & "\7z.exe" &...

Instead of commenting out the entire 7zip check only comment out the IF and EndIf lines to make sure that the registry lookup happens.

so i commented out the following:

' If Err.number 0 then

' errNoSevenZip = "The Backup Script for VMware Server couldn't find the 7-zip Application installed on your system." & VbCrLf & "Please visit 7zip.org to get it."

' wshShell.LogEvent 1, errNoSevenZip

' mailing.Subject = header & ": Install 7-zip"
' mailing.TextBody = errNoSevenZip
' mailing.Configuration.Fields.Update
' mailing.Send
' If args.Count=0 Then
' crySevenZip = msgBox(errNoSevenZip,vbCritical,header)
' End If

' WScript.Quit

' end if

so what i unc-ommented out was:
seven_zip_reg = wshShell.RegRead("HKLM\SOFTWARE\7-Zip\Path")

----------------------
I ran the script and it asked me for the location of my vmx file so i gave it than it prompted me again for where i wanted to save it and i clicked ok but after that it did nothing....

it gave me an error saying: "the backup script for vmware couldnt create an apportiate connection........)

anything else????


It's an unrelated error. Strange coincidence though. While I understand most of the code this "server connection" is one piece i still don't fully understand. I'd just try running again.

p.s. A better way to "fix" the 7zip error check issue you have would be to put the entire section back to what it was originally (uncomment everything you commented) and add "err.clear" before this line:

seven_zip_reg = wshShell.RegRead("HKLM\SOFTWARE\7-Zip\Path")

This will ensure any previous errors are ignored and if you get a 7zip error it really is a 7zip error.

Hello,

please could you do the following:

leave the script unchanged (leave your paths inside).

Click Start > Run

Enter the following into the command line:

codeC:\Windows\SysWoW64\wscript.exe vm-backup.vbs[/code]

and see if it says anything about 7zip.

If it does, please do the following.

Find

code
seven_zip_reg = wshShell.RegRead("HKLM\SOFTWARE\7-Zip\Path")

If Err.number 0 then

errNoSevenZip = "The Backup Script for VMware Server couldn't find the 7-zip Application installed on your system." & VbCrLf & "Please visit 7zip.org to get it."

wshShell.LogEvent 1, errNoSevenZip

mailing.Subject = header & ": Install 7-zip"
mailing.TextBody = errNoSevenZip
mailing.Configuration.Fields.Update
mailing.Send
If args.Count=0 Then
crySevenZip = msgBox(errNoSevenZip,vbCritical,header)
End If

WScript.Quit

end if
[/code]

and replace with

code
seven_zip_reg = "C:\Program Files\7-zip"
[/code]

If after this editing the script doesn't do which it's supposed to, I would like to test something else.

Message was edited by:
saxa


While I understand most of the code this "server connection" is one piece i still don't fully understand.

Which one?

If you're on 64bit:

My script, which must be executed in 32bit context, at the stage of compressing tries to run a 64bit executable. I think, that's a problem.

@Louch: maybe you could swap your host system to 32bit?

Joking aside, I would try to uninstall the 64bit version of 7-zip and install the 32bit one.

Just not sure what this is really doing. My guess is that it's connecting to the Vcom API objects in preparation to connect to the virtual machines.

I downloaded the API docs, but have not gotten a chance to read them yet. I'm currently working on an addition to delete older backups after a new backup is successfully created.

' Try to connect to server 10 times

connected = False
For tries_srv = 1 To 10
server.Connect cp
If Err.number = 0 Then
connected = True
Exit For
End If
WScript.Sleep 10000
Err.clear
Next


Louch, are you from Germany?

My guess is that it's connecting to the Vcom API objects in preparation to connect to the virtual machines.

Almost correct.

It connects to VMware Server.

If you are working with SQL database, you have to connect to server prior to connect to database, right?

Saxa: after chaning the path to 7-zip directly in the config it started to work!!! thanks a bunch for ur help!!! this thing works great!!!!!!!!!!!!!!!

to answer your last question, im from Canada

p.s. to everyone else thx for all your help!!!!! this script does truley rock!

Hello,

glad it works for you!

to answer your last question, im from Canada

I know somebody here in Germany who's name is Louch, it's quite rare name here; that's why I asked you about your location. :)

I wrote a subroutine for this script that will automatically delete older backup zips. I offer it here for anyone who would like to use it.

The subroutie will not be called unless the variable "CleanUpBackupFiles" is true. Simply put it gets a list of all the backup files (zips) in the backup folder which are for the VM being backed up and are of at least a specified filesize. It then sorts them by date and keeps the most recent number requested and deletes the rest. It may not be the most elegant code but it gets the job done.

First are some comments that should go in the comments section at the top of the script:
code
'The code to delete old backup files will incorrectly delete files if one virtual machine identifier is a beginning substring
'of another. Ie: machine1 identifier = "VM10"; machine2 identifier = "VM10-1" (don't do this). Us this option at your own risk.
'
[/code]

Next are the variables the sub uses.
code
'Define cleanup options for the backup file
CleanUpBackupFiles = false 'Should the script delete old backup files for this VM upon sucessfull backup
'The following are Only needed if the above value is true
NumberBackupsToKeep = 3 'Maximum number of backups per VM to keep. Oldest backups above this number are deleted
MinFileSize = 1000 'Minimum file size (MB) for an existing backup file to be considered valid
[/code]
You can paste this just before
code
On Error Resume Next

' Common definitions...

Set wshShell = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
Set cp = CreateObject("VmCOM.VmConnectParams")
Set server = CreateObject("VmCOM.VmServerCtl")
Set thevm = CreateObject("VmCOM.VmCtl")
Set wshNet = CreateObject("WScript.Network")
Set mailing = CreateObject("CDO.Message")
[/code]

The following is the main code:
code
Sub Delete_Old_Backup_Files (byval VMName, byval BackupFolder)
'*******************************************************************************************
'Deletes older backup files to conserve disk space.
'*******************************************************************************************
On Error Resume Next

set FSO = createobject("scripting.filesystemobject")
set Folder = FSO.getfolder(BackupFolder)
set Files = Folder.Files
Dim NFileArray ()
Dim MFileArray ()

'Initialize values now that we can
RealFileCount = Folder.Files.Count
redim NFileArray (RealFilecount)
redim MFileArray (RealFileCount)

'Fetch the list of files
MyFileCount = 0
for each file in Files
' Only files matching the VM identifier count
if strcomp (left(file.name, (len(VMName)+1)), VMName & "-",1) = 0 then
'Only files bigger than "x" MB in size count
if file.size >= MinFileSize * (1024 * 1024) then
MyFileCount = MyFileCount + 1
NFileArray(MyFileCount) = file
MFileArray(MyFileCount) = File.DateLastModified
end if
end if
next

'No sense doing anything else if less files then max allowed
if MyFileCount > NumberBackupsToKeep then
'Sort by modified date
for i = 1 to MyFileCount
for j = (i + 1) to MyFileCount
if MFileArray(i) < MFileArray(j) then
NBuffer = NFileArray(j)
MBuffer = MFileArray(j)
NFileArray(j) = NFileArray(i)
MFileArray(j) = MFileArray(i)
NFileArray(i) = NBuffer
MFileArray(i) = MBuffer
end if
next
next
'Delete part
for n = NumberBackupsToKeep + 1 to MyFileCount 'Array position zero is blank
Set Deletefile = FSO.getfile(NfileArray(n))
Deletefile.delete true
next
end if

end sub
[/code]
This can be pasted just before
code
Function iso_date(byval dt)

' The function does nothing interesting...

dim y: y=year(dt)
dim m: m=month(dt)
dim d: d=day(dt)
dim h: h=hour(dt)
dim n: n=minute(dt)
dim s: s=second(dt)

if m < 10 then m="0" & m
if d < 10 then d="0" & d
if h < 10 then h="0" & h
if n < 10 then n="0" & m
if s < 10 then s="0" & s

iso_date = y & "-" & m & "-" & d & "-" & h & n & s

end Function
[/code]

Finally here is the code which calls the sub:
code
'if enabled, delete backups not needed any more
if CleanUpBackupFiles then
Delete_Old_Backup_Files vm, fso.GetParentFolderName(zipfile)
end if
[/code]
It should be pasted right before this:
code
' Calculate time used...

time_off = DateDiff("n",checkpoint_begin,checkpoint_started)
time_cmp = DateDiff("n",checkpoint_started,checkpoint_ready)
time_sum = time_off + time_cmp
[/code]


Not bad!

MinFileSize * (1024 * 1024)

:) about the brackets...

Not bad!

Thank you

:) about the brackets...

Yeah, I can be a bit anal. While not necessary stupid stuff like this helps me read and understand the code better.

While not necessary stupid stuff like this helps me read and understand the code better.

Agree!

this might be a silly question but the current orginal script Saxa wut does it do with older files? does it keep them all or does it delete some after a period?

also i can't get it to email me when its done the backup for some reason... i put in my exchange server ip and also email addresses. n e thing else i need to do?

this might be a silly question but the current
orginal script Saxa wut does it do with older files?
does it keep them all or does it delete some after a
period?

It keeps them all

also i can't get it to email me when its done the
backup for some reason... i put in my exchange server
ip and also email addresses. n e thing else i need to
do?

The script assumes your mail server is using port 25 (which it probably is)
Can the machine running the script talk to the exchange server?

From command prompt try: "telnet <exchange IP address> 25"

If you get a response it's not a networking/firewall issue.

Will your exchange server relay mail from the IP address of the machine running the script?

this might be a silly question

There are no silly questions, there are only silly answers (c)

My original script doesn't do anything with old files = keeps them all.

also i can't get it to email me when its done the backup for some reason...

Unfortunately I haven't a 64bit Windows to test it...

Could you check if you have a cdosys.dll in the %WINDIR%\syswow64 directory? This file is responsible for sending of mails.

I send my mails to some dummy SMTP server running on linux; it routes mails to real server (also Exchange).

One more idea:

i put in my exchange server ip

Try to put the FQDN of it instead, as the server is seen from the internet.

And one more:

Some antivirus applications do not allow to open connections to/from port 25. E.g. McAfee by default...

forgot about the 64 bit part

Will your exchange server relay mail from the IP address of the machine running the script?

I would say "Will your exchange server accept mail" from that, sure it is, private, IP address.

MinFileSize * (1024 * 1024)

:) about the brackets...


Perhaps this is better. Since I used it a few more times I decided to make it a constant (and actually changed to GB).

In this code it's used to calculate additional statistics which I use in the success message. This also lets me create warnings if disk space is running low.
code
'Calculate statistics
set zf = fso.getfile(zipfile)
ZipFileSize = round(zf.size / OneGB, 2)
set bddrv = fso.getdrive(zf.drive)
BackupDriveFreeSpace = round(bddrv.availablespace / OneGB, 2)
set vmfl = fso.getfile (vmfile)
set vmfldr = fso.getfolder(vmfl.parentfolder)
VMSize = round(vmfldr.size / OneGB, 2)
[/code]

Sample output:
code
The VMware Backup Script backed up the virtual machine D:\Virtual Machines\Manage\Windows XP Professional.vmx successfully.

Backup saved as D:\backups\Manage-2006-11-29-152724.zip.
VM was offline 13 minutes between 3:27:27 PM and 3:40:34 PM.
The compress operation took 35 minutes.

The VM is approximately 8.25GB.
The zip file is approximately 2.31GB.
There is currently 25GB free on the backup location.

Total run time was 48 minutes.
Start Time: 11/29/2006 3:27:27 PM.
End Time: 11/29/2006 4:15:29 PM.
[/code]

Yeah, it's excellent!

Especially this ones:

code
The zip file is approximately 2.31GB.
There is currently 25GB free on the backup location.
[/code]

Maybe could you keep the ISO-conform time formatting?

Maybe could you keep the ISO-conform time formatting?

Are you talking about this line?
code
VM was offline 13 minutes between 3:27:27 PM and 3:40:34 PM.
[/code]

If so, I only wanted the time. Is there a reason to do it otherwise?

codeVM was offline 13 minutes between 15:27:27 and 15:40:34.[/code]

It's international :)

codeVM was offline 13 minutes between 15:27:27 and
15:40:34.[/code]

It's international :)


Damn American Pigs! :)
Figured it was something like that. You're right, I'll have to figure out how to do that.

Use the iso_date function or some parts of it.

Use the iso_date function or some parts of it.

Ok, I replaced iso_date with this:
code
Function ISO_DateTime (byval dt, byval dttype, byval NoSpecialChars)
'*******************************************************************************************
'Converts dates/Times to ISO format
'First parameter is the date/time
'Second is the type of conversion: 1=Date Only, 2=Time only, anything else does both
'Third determines if the ":" can appear in the time
'*******************************************************************************************
On Error Resume Next

dim y: y=year(dt)
dim m: m=month(dt)
dim d: d=day(dt)
dim h: h=hour(dt)
dim n: n=minute(dt)
dim s: s=second(dt)

if m < 10 then m="0" & m
if d < 10 then d="0" & d
if h < 10 then h="0" & h
if n < 10 then n="0" & m
if s < 10 then s="0" & s

'Handle Date
TheDate = y & "-" & m & "-" & d
'Handle Time
if NoSpecialChars then
TheTime = h & n & s
else
TheTime = h & ":" & n & ":" & s
end if
'Combine for Date/Time
TheDateTime = TheDate & "T" & TheTime

'Return whichever value the user wanted
if dttype = 1 then
ISO_DateTime = TheDate
elseif dttype = 2 then
ISO_DateTime = TheTime
else
ISO_DateTime = TheDateTime
end if

end Function
[/code]
Note: From what i could tell ISO 8601 requires the "T" between the date and time.

Here is the output now:
code
The VMware Backup Script backed up the virtual machine D:\Virtual Machines\Manage\Windows XP Professional.vmx successfully.

Backup saved as D:\backups\Manage-2006-11-29T183818.zip.
VM was offline 13 minutes between 18:38:20 and 18:51:37.
The compress operation took 35 minutes.

The VM is approximately 8.25GB.
The zip file is approximately 2.31GB.
There is approximately 25GB free on the backup location.

Total run time was 48 minutes.
Start Time: 2006-11-29T18:38:20.
End Time: 2006-11-29T19:26:04.
[/code]

This is one of my older emails while I was testing and didn't have the free space calculation working. It shows the disk space warning which is now possible . (I also have a warning when there might be a problem)
code
The VM is approximately 8449MB.
The zip file is approximately 2364MB.
There is currently MB free on the backup location.

*** THERE IS NOT ENOUGH FREE DISK SPACE TO BACKUP AGAIN! ***

Total run time was 49 minutes.
Start Time: 11/29/2006 1:44:21 PM.
End Time: 11/29/2006 2:33:18 PM.
[/code]


Hello,

thank you for this cool script.

Here i found a script for Microsofts Virtual Server which backups a VM with minimal downtime.
http://cwashington.netreach.net/depo/view.asp?Index=1049&ScriptType=vbscrip

Its stops or pauses the machine, creates a shadow copy, starts it again, and then is copying the files. Did anybody try something like that with VMWare Server and Shadow copies?

Alex

Hello Alex,

Here i found a script for Microsofts Virtual Server which backups a VM with minimal downtime.

Fine. Already tried it out?

[sarcastic mode on]

I love it!

code
sExCmd = "CreateVSS.cmd"
[/code]

Hm... what does that cmd file?

The script is quite good commented, you can read it.

[sarcastic mode off]

Did anybody try something like that with VMWare Server and Shadow copies?

I didn't. Why should I? The difference between 1 and 8 minutes downtime is not soooo big. It's downtime anyway.

The target of my script is a high compliance: there are admins here running VMware Server on W2K, which doesn't have a possibility to create shadow copies.

Over the above the script should also handle Linux driven hosts...

But the source code is here; you are free to develop this feature and show it here!

What originally started as an effort to format the script so that I could read and understand it better turned into a fairly significant reorganization.

I am posting my work for anyone who might be interested.

I call it a reorganization because I really didn't make many core changes to what the original code was doing. It's all still there, with a couple of extra features.

* Added disk space statistics to show the size of the compressed and uncompressed VM as well as free space on the backup location.

Any comments are certainly welcome.

code
'Copyleft saxa aka Alexander Kaufmann, 2006
'Butchered by SirShagg, 2006

'By all means, completely ignore the following :)
'***********************************************************************************************************************************
'Written just for fun, total Open Source, Use it at your own risk, and whatever else don't blame me if you have problems.
'
'The script uses the VmCOM API for the virtual machine operations. You must have this installed separately if
'VMware server is not installed on the machine running this script (ie: backing up remote virtual machines)
'
'The virtual machine *must* have the VMware Tools installed, in order to backup running virtual machines.
'
'The script will work on Windows 2000 SP4 and newer. It was also successfully tested on Vista.
'
'Plese keep in mind the strangeness of the script execution on 64bit Windows - there is no VmCOM 64bit,
'so you have to run it in 32bit context. See your Windows Help for details.
'
'The script can be applied to a local host or to remote host: see the remote_server variable.
'The script *can* backup to the network share, if you have the appropriate permissions to write on it.
'
'The most important thing for remote execution: You have to share your Virtual Machines directory on the host. The user who
'runs the script (not the remote_user) must have the read permissions on that share. For Linux users: install and configure
'Samba...For Windows users: hidden shares?!
'
'For the backup jobs the script uses the command line version of 7zip. Get it on http://7zip.org/download.html.
'Just download the full install - there is also a 64 bit version available.
'
'The subdirectory where the virtual machine is located is very important for this script: it's the virtual machine's identifier.
'It will become the part of the name of the zip file.
'
'The code to delete old backup files will incorrectly delete files if one virtual machine identifier is a beginning substring
'of another. Ie: machine1 identifier = "VM10"; machine2 identifier = "VM10-1" (don't do this). Us this option at your own risk.
'

'*************************************************
'The script will do the following (simplified):
'*************************************************
'The VMware Tools inside the virtual machine receives the command to shut down the operating system. The script waits a
'set period of times and checks the state of the virtual machine. If the vm is still running then the script waits some more and
'checks again. This continues untill the VM is off or a timeout occurs (failure). As soon as the vm is off, the script
'creates a copy of the vm's folder to the backup location. After the copying is done, the vm receives the command to start
'if it was running before the operation had begun. The script then checks that the VM is up and running in much the same way it
'checked if it had been shut down. As soon as the VM is confirmed running the script starts to create a compressed archive
'from a previously copied vm directory. After the .zip file has been created, the script checks if there were any errors
'produced by 7zip and if not the copied VM files are deleted and we are left with just the zip file. Next the script checks if
'any older zip files (backups) can be deleted.
'
'The .zip archive will be named as: Virtual Machine Identifier-YYYY-MM-DD-HHMMSS.zip. The creation of the .zip file takes it's sweet
'time: on Pentium 4 (with Hyperthreading, single core) 2.8 GHz machine with 3GB RAM, the compress operation on a virtual
'machine having 2 virtual HDDs at 16 and 36 GB was about 2 hours.
'
'Throughout this process error checks are made and noted with emails sent to the administrator.

'*********************************************************************************
'You will start the script as follows (substitute your own path and file name):
'*********************************************************************************
'vm-backup.vbs "D:\Virtual Machines\Virtual Machine 1\vm.vmx" (this is interactive mode)
'
'If you want to use the script in a sheduled task, please use the following command line:
'
'wscript.exe vm-backup.vbs "D:\Virtual Machines\Virtual Machine 1\vm.vmx"
'or if you also want ot specify the backup file manually
'wscript.exe vm-backup.vbs "D:\Virtual Machines\Virtual Machine 1\vm.vmx" "D:\Backup\myvmbackup.zip"

On Error Resume Next
'***********************************************************************************************************************************
' All the values that you need to specify are conveniently located in this section.
'***********************************************************************************************************************************

'Define the default VM path (for interactive mode only)
DefaultVMPath = "D:\Virtual Machines\" 'Relative to VMware host. Need read permissions

'Define the default destination for backup files
DefaultBackupPath = "D:\backups\" 'Relative to the machine running the script, UNC is OK. Need write permissions

'Define cleanup options for the backup files
CleanUpBackupFiles = false 'Should the script delete old backup files for this VM upon sucessfull backup
'Set MinFileSize even if the above value is false (used to check is archive is valid)
NumberBackupsToKeep = 7 'Maximum number of backups per VM to keep. Oldest backups above this number are deleted
MinFileSize = 1 'Minimum file size (gb) for an existing backup file to be considered valid

'Define optional compression switches
seven_zip_switch = "" 'Optional switches for use with 7Zip, perhaps " -v4g" See the 7zip manual

'Define your mail settings
ReportToMail = "admin@mydomain.com" 'Here you'll receive mail messages.
MyMailDomain = "mydomain.com" 'Your mail domain name
SMTPServer = "smtp.mydomain.com" 'IP address or host name. Server must be able to relay mails for your address
SMTPPort = 25 '25 is standard
DefaultMailSubject = "" 'Subject line for email message, end with ": " if used. (the script code adds to this)

'Define remote server values
remote_server = false 'Set to true if backing up VM on another machine
'The following are Only needed if the above value is true
remote_host = "192.168.0.101" 'IP address or host name
remote_port = "902" '902 is standard
remote_user = "root" 'User on the remote server who may run the VM's
remote_pass = "password" 'User's password
remote_share = "\\server\share\Virtual Machines"'User running script must have read permission

'Define other values (defaults should be fine)
ServerConnectMaxTries = 10 'Number of attempts to connect to the server
ServerConnectTryInterval = 1 'Seconds between attempts to connect to the server
VMConnectMaxTries = 10 'Number of attempts to connect to the VM
VMConnectTryInterval = 1 'Seconds between attempts to connect to the VM
VMStopMaxTries = 10 'Number of attempts to stop the VM
VMStopTryInterval = 60 'Seconds between attempts to stop the VM
VMStartMaxTries = 20 'Number of attempts to start the VM
VMStartTryInterval = 30 'Seconds between attempts to start the VM
VMStartedHeartbeat = 300 'Number of heartbeats needed to confirm the VM started

'Free Disk Space Warning values
FreeDiskSpaceCriticalThreshold = 100 'Critical message when free disk space is below this % of the vmsize + backup size
FreeDiskSpaceWarningThreshold = 120 'Warning message when free disk space is below this % of the vmsize + backup size

'Define your error messages
'Messages can have multiple lines and can include any variable used in the script.
'
'How to define messages:
'MyMessageLines = 4 'This says the message "MyMessage" has three lines (change as the # of lines changes)
'MyMessage1 = "Here is line 1" 'This is the first line of the message (numbering should start at 1)
'MyMessage2 = "" 'This is the second line of the message (inserts a blank line in the message)
'MyMessage3 = "Here is line 3__" 'This is the third line of the message (the "__" at the end indicates no line feed.
'MyMessage4 = "Here is line 4" 'This is the third line of the message
'
'NOTE: "MyMessage" is the identifier for this message
'
'
'In order insert variables into the message you must prepend them with "%\^" and end them with "^%"
'Example: the variable vmfile would be %\^vmfile^%
'
'It's possible that you could inset a variable in a message that appears before the varialble value is defined.
'If this is the case the variable will print as "", no biggie. Is shouldn't happen because it wouldn't make sense but who knows.
'Example: us %\^VMRestarted^% in the VMShutdownErrorMessage. (if we errored out shutting down how could we have restarted)
'
'In addition to the variables above you may also want to use:
'VMFile = The name of the virtuial machine file
'VMFolder = The name of the folder where the virtual machine is located
'VMIdentifier = the virtual machine identifier (the folder that the vmfile is in)
'BackupPath = The folder where backup are created
'BackupDriveFreeSpace = The amount of free space (in gb) on the backup drive
'ZipFile = The backup file that is created
'TimeVMOff = The amount of time the VM was shutdown for the operation
'TimeCompressing = The time spent compressing the backup file
'TimeTotal = The total time spent on the backup operation
'VMsize = The size (in GB) of the Virtual Machine
'ZipFileSize = The size (in GB) of the backup file
'BackupDriveFreeSpace = The amount of free space (in GB) on the backup destination
'VMShutdownStart = The date/time when the VM was shutdown
'VMRestarted = The date/time when the VM was restarted
'ArchiveCreated = The date/time when the operation was complete
'TimeVMShutdownStart = The time when the VM was shutdown
'TimeVMRestarted = The time when the VM was restarted
'TimeArchiveCreated = The time when the operation was complete

VariablesErrorMessageLines = 3
VariablesErrorMessage1 = "It appears that there are problems in the section where the variables are defined.__" 'this section
VariablesErrorMessage2 = "Most likely a '""' has been forgotten somewhere.__"
VariablesErrorMessage3 = "Please check all the values and make sure they are correct."

VCOMErrorMessageLines = 2
VCOMErrorMessage1 = "It appears that there are problems with the VCOM API.__"
VCOMErrorMessage2 = "Either it's not installed, you are running on a 64bit system, or something else is wrong with it."

No7ZipInstalledErrorMessageLines = 2
No7ZipInstalledErrorMessage1 = "The VMware Backup Script couldn't find the 7-zip Application installed on your system.__"
No7ZipInstalledErrorMessage2 = "Please visit 7zip.org to get and install it."

InvalidArguementsMessageLines = 3
InvalidArguementsMessage1 = "Incorrect Input. The directory where the Virtual Machine files are located must be provided as argument.__"
InvalidArguementsMessage2 = "If the directory name contains spaces, please add the '""' character at the beginning and at the end of the Virtual Machine's name.__"
InvalidArguementsMessage3 = "The reading of the source code of the vm-backup.vbs script may also help ;)"

InsufficientDriveSpaceErrorMessageLines = 4
InsufficientDriveSpaceErrorMessage1 = "There is not enough free space on %\^BackupPath^% to backup the virtual machine '%\^VMIdentifier^%'."
InsufficientDriveSpaceErrorMessage2 = ""
InsufficientDriveSpaceErrorMessage3 = "The VM is approximately %\^VMsize^% GB."
InsufficientDriveSpaceErrorMessage4 = "There is only %\^BackupDriveFreeSpace^% GB free space available."

NoServerConnectionErrorMessageLines = 2
NoServerConnectionErrorMessage1 = "The VMware Backup Script couldn't create an appropriate connection to the server.__"
NoServerConnectionErrorMessage2 = "Please check if all of the VMWare Services are up and running."

NoVMConnectionErrorMessageLines = 2
NoVMConnectionErrorMessage1 = "The VMware Backup Script couldn't connect to the virtual machine '%\^vmfile^%'.__"
NoVMConnectionErrorMessage2 = "Please check that the path is correct and that the virtual machine is registered on your server."

VMStateErrorMessageLines = 2
VMStateErrorMessage1 = "The VMware Backup Script couldn't get the correct state of the virtual machine '%\^VMIdentifier^%'.__"
VMStateErrorMessage2 = "Correct states are on and off only. A virtual machine with pending question, such as new SID after copying or moving also can't be backed up."

VMWareToolsErrorMessageLines = 2
VMWareToolsErrorMessage1 = "The VMware Backup Script couldn't contact the VMWare Tools on the virtual machine '%\^VMIdentifier^%'.__"
VMWareToolsErrorMessage2 = "Because of this the VM cannot be shut down correctly. Please shut down the virtual machine manually. Afterwards it can be backed up."

VMShutdownErrorMessageLines = 2
VMShutdownErrorMessage1 = "The VMware Backup Script couldn't shut down the virtual machine '%\^VMIdentifier^%' in a reasonable time.__"
VMShutdownErrorMessage2 = "Please check it's state."

VMStartupErrorMessageLines = 4
VMStartupErrorMessage1 = "The VMware Backup Script couldn't power on the virtual machine '%\^VMIdentifier^%' in a reasonable time.__"
VMStartupErrorMessage2 = "Maybe the machine could not start the VMWare Tools. Please check it's state and/or configuration."
VMStartupErrorMessage3 = ""
VMStartupErrorMessage4 = "Backup processing will continue and you should expect another message."

ArchiveCreationErrorMessageLines = 4
ArchiveCreationErrorMessage1 = "The VMware Backup Script couldn't create %\^ZipFile^%.__"
ArchiveCreationErrorMessage2 = "Please check if you have enough disk space on %\^BackupPath^% and run the backup script again."
ArchiveCreationErrorMessage3 = ""
ArchiveCreationErrorMessage4 = "Note: The uncompressed virtual machine files were NOT deleted from %\^BackupPath^%."

ZipFileSizeErrorMessageLines = 7
ZipFileSizeErrorMessage1 = "The compress operation completed successfully however the zip file is smaller than expected.__"
ZipFileSizeErrorMessage2 = "Please check that all files were compressed and exist in %\^ZipFile^%.__"
ZipFileSizeErrorMessage3 = "Also check that there is enough disk space on %\^BackupPath^%."
ZipFileSizeErrorMessage4 = ""
ZipFileSizeErrorMessage5 = "The zip file is approximately %\^ZipFileSize^% GB."
ZipFileSizeErrorMessage6 = "The zip file was expected to be over %\^MinFileSize^% GB."
ZipFileSizeErrorMessage7 = "Note: The uncompressed virtual machine files were NOT deleted from %\^BackupPath^%."

FreeDiskSpaceCriticalLines = 1
FreeDiskSpaceCritical1 = "*** THERE IS NOT ENOUGH FREE DISK SPACE TO BACKUP AGAIN! ***"

FreeDiskSpaceWarningLines = 1
FreeDiskSpaceWarning1 = "*** There may not be enough free disk space to backup again. ***"

SuccessMessageLines = 13
SuccessMessage1 = "The VMware Backup Script backed up the virtual machine '%\^VMIdentifier^%' successfully."
SuccessMessage2 = ""
SuccessMessage3 = "Backup saved as %\^ZipFile^%."
SuccessMessage4 = "VM was offline %\^TimeVMOff^% minutes between %\^TimeVMShutdownStart^% and %\^TimeVMRestarted^%."
SuccessMessage5 = "The compress operation took %\^TimeCompressing^% minutes."
SuccessMessage6 = ""
SuccessMessage7 = "The VM is approximately %\^VMsize^% GB."
SuccessMessage8 = "The zip file is approximately %\^ZipFileSize^% GB."
SuccessMessage9 = "There is approximately %\^BackupDriveFreeSpace^% GB free on the backup location."
SuccessMessage10 = ""
SuccessMessage11 = "Total run time was %\^TimeTotal^% minutes."
SuccessMessage12 = "Start Time: %\^VMShutdownStart^%."
SuccessMessage13 = "End Time: %\^ArchiveCreated^%."

'***********************************************************************************************************************************
'No need to touch anything after this point
'***********************************************************************************************************************************
Const vmExecutionState_On = 1
Const vmExecutionState_Off = 2
Const vmExecutionState_Suspended = 3
Const vmExecutionState_Stuck = 4
Const vmExecutionState_Unknown = 5
Const vmPowerOpMode_Hard = 1
Const vmPowerOpMode_Soft = 2
Const vmPowerOpMode_TrySoft = 3

Const OneMB = 1048576
Const OneGB = 1073741824
Const OneSecond = 1000

'Create objects
Set mailing = CreateObject("CDO.Message")
Set wshNet = CreateObject("WScript.Network")
Set wshShell = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")

'Uncomment to test messages
'Setup_Mail_System ("")
'Error_Encountered Build_Message("VariablesErrorMessage"),true

'Check for errors (decent chance of a typo in all those messages above)
If Err.number 0 then
Setup_Mail_System ("")
Error_Encountered Build_Message("VariablesErrorMessage"),true
end if

'Create VMCOM objects
Set cp = CreateObject("VmCOM.VmConnectParams")
Set server = CreateObject("VmCOM.VmServerCtl")
Set thevm = CreateObject("VmCOM.VmCtl")

'Check for VCOM errors
If Err.number 0 then
Setup_Mail_System ("")
Error_Encountered Build_Message("VCOMErrorMessage"),true
end if


Function Build_Message (byval Message)
'*******************************************************************************************
'Builds a message to be displayed to the user. It Takes a single string parameter "x".
'It looks for variables defined as X + "Lines" and X + <number>.
'X + "lines" is the number of lines for the message and each X + <number> is a message line.
'It loops through all the message lines to build the message. Message lines can contain
'variables which must be preceeded by "%\^" and followed by "^%". The variables will be
'decoded and and their current value will be inserted into the message.
'*******************************************************************************************
On Error Resume Next

'Initialize temp value
TempMessage = ""
'Get number of lines in message
j = eval(cstr(Message) + "Lines")
'Loop through all the message lines
for i = 1 to j
'Get a message line
Junk = eval(cstr(Message) + cstr(i))
'Handle line feeds
if right (Junk, 2) = "__" then
Junk = left (Junk, len (Junk) -2) & " "
else
Junk = Junk & vbcrlf
end if
'Get position of variable in message line
pos1 = instr (1, Junk, "%^")
Pos2 = instr (1, Junk, "^%")
'Process all variables in the message line
while pos1 + pos2 > 0
'Get the variable name
var = mid(Junk, pos1 +2, (pos2 - pos1) - 2)
'replace the varialbe placeholder with the variable name
Junk = replace(Junk, "%\^" & var & "^%", eval(var))
'Check for more variables in the line
pos1 = instr (1, Junk, "%^")
Pos2 = instr (1, Junk, "^%")
wend
'Add the message line to the complete message
TempMessage = TempMessage & Junk
next
'Return the complete message
Build_Message = TempMessage

end function

Sub Delete_Old_Backup_Files (byval VMName, byval BackupFolder)
'*******************************************************************************************
'Deletes older backup files to conserve disk space.
'*******************************************************************************************
On Error Resume Next

set FSO = createobject("scripting.filesystemobject")
set Folder = FSO.getfolder(BackupFolder)
set Files = Folder.Files
Dim NFileArray ()
Dim MFileArray ()

'Initialize values now that we can
RealFileCount = Folder.Files.Count
redim NFileArray (RealFilecount)
redim MFileArray (RealFileCount)

'Fetch the list of files
MyFileCount = 0
for each file in Files
'Only files matching the VM identifier count
if strcomp (left(file.name, (len(VMName)+1)), VMName & "-",1) = 0 then
'Only files bigger than "x" GB in size count
if file.size >= (MinFileSize * OneGB) then
MyFileCount = MyFileCount + 1
NFileArray(MyFileCount) = file
MFileArray(MyFileCount) = File.DateLastModified
end if
end if
next

'No sense doing anything else if less files then max allowed
if MyFileCount > NumberBackupsToKeep then
'Sort by modified date
for i = 1 to MyFileCount
for j = (i + 1) to MyFileCount
if MFileArray(i) < MFileArray(j) then
NBuffer = NFileArray(j)
MBuffer = MFileArray(j)
NFileArray(j) = NFileArray(i)
MFileArray(j) = MFileArray(i)
NFileArray(i) = NBuffer
MFileArray(i) = MBuffer
end if
next
next
'Delete part
for n = NumberBackupsToKeep + 1 to MyFileCount 'Array position zero is blank
Set Deletefile = FSO.getfile(NfileArray(n))
Deletefile.delete true
next
end if

'Destroy objects
set FSO = nothing
set Folder = nothing
set Files = nothing

end sub

Sub Setup_Mail_System (byval VMName)
'*******************************************************************************************
'Setup the mail system. Made into becasue I wanted to send notification if the arguements
'passed to the script were bad.
'*******************************************************************************************
On Error Resume Next

mailing.To = ReportToMail
if VMName is not null then
mailing.from = "VM-" & ucase(VMName) & "@" & MyMailDomain
else
mailing.from = "VM-**Unknown**" & "@" & MyMailDomain
end if
mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = SMTPServer
mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = SMTPPort

end sub

sub Error_Encountered (byval ErrorMessage, byval StopError)
'*******************************************************************************************
' Write a message to the application log, send email (& messagebox if interactive) and quit
'*******************************************************************************************
On Error Resume Next

wshShell.LogEvent 1, ErrorMessage
if StopError then
mailing.Subject = DefaultMailSubject & "Critical Error"
else
mailing.Subject = DefaultMailSubject & "Warning"
end if
mailing.TextBody = ErrorMessage
mailing.Configuration.Fields.Update
mailing.Send
If way="i" Then
Cry = msgBox(ErrorMessage,vbCritical,DefaultMailSubject)
End If
if StopError then
Destroy_Objects
WScript.Quit
end if

end sub

Function ISO_DateTime (byval dt, byval dttype, byval NoSpecialChars)
'*******************************************************************************************
'Converts dates/Times to ISO format
'First parameter is the date/time
'Second is the type of conversion: 1=Date Only, 2=Time only, anything else does both
'Third determines if the ":" can appear in the time
'*******************************************************************************************
On Error Resume Next

dim y: y=year(dt)
dim m: m=month(dt)
dim d: d=day(dt)
dim h: h=hour(dt)
dim n: n=minute(dt)
dim s: s=second(dt)

if m < 10 then m="0" & m
if d < 10 then d="0" & d
if h < 10 then h="0" & h
if n < 10 then n="0" & n
if s < 10 then s="0" & s

'Handle Date
TheDate = y & "-" & m & "-" & d
'Handle Time
if NoSpecialChars then
TheTime = h & n & s
else
TheTime = h & ":" & n & ":" & s
end if
'Combine for Date/Time
TheDateTime = TheDate & "T" & TheTime

'Return whichever value the user wanted
if dttype = 1 then
ISO_DateTime = TheDate
elseif dttype = 2 then
ISO_DateTime = TheTime
else
ISO_DateTime = TheDateTime
end if

end Function

sub Destroy_Objects ()
'*******************************************************************************************
'Destroy the various objects we created. Made into a sub because the script quits from
'more then one place (if errors).
'*******************************************************************************************
On Error Resume Next

'Destroy objects
Set mailing = nothing
Set wshNet = nothing
Set wshShell = nothing
Set fso = nothing
Set thevm = Nothing
Set server = Nothing
Set cp = Nothing
set VMFolderObject = nothing
set BackupDriveObject = nothing
set ZipFileObject = nothing
set args = nothing
WScript.Sleep 2 * OneSecond

end sub


'Check if 7zip is installed
Err.clear
seven_zip_reg = wshShell.RegRead("HKLM\SOFTWARE\7-Zip\Path")
'Check for errors
If Err.number 0 then
Setup_Mail_System ("")
Error_Encountered Build_Message("No7ZipInstalledErrorMessage"),true
end if

'Get the name of the VM delivered by the script argument. Number of arguements must be between 0-2
'If none, then prompt the user for values
'If one, then the user only specified the VM to backup and use default backup file
'If two, then the user wants to define the VM to backup and backup file manually
'If three or more than there is something wrong
Set args = WScript.Arguments
if args.count=0 then 'We are in the interactive mode, way = "i(nteractive)"
'Prompt for the name of the vmfile
vmfile = inputBox("Please enter the full path to the .vmx file of the virtual machine you want to backup:",DefaultMailSubject,DefaultVMPath)
'Quit if cancel
if vmfile = "" then
Destroy_Objects
WScript.Quit
end if
'Determine the VM Identifier based on the vmfile location
VMFolder = fso.GetparentFoldername(vmfile)
set VMFolderObject = fso.Getfolder (VMFolder)
VMIdentifier = VMFolderObject.name
'prompt for the name of the zipfile
TempValue = DefaultBackupPath & VMIdentifier & "-" & ISO_DateTime(now, 0, true) & ".zip"
ZipFile = inputBox("Now, please enter the full path to the .zip file the script will create:",DefaultMailSubject,TempValue)
'Quit if cancel
if ZipFile = "" then
Destroy_Objects
WScript.Quit
end if
'Determine the location where the temporary backup files will be saved
BackupPath = fso.GetParentFolderName(ZipFile) & "\" & VMIdentifier
way = "i"
elseIf args.Count=1 Then 'We are in the mode with predefined vm by parameter, way = "a(utomatic)"
vmfile = args(0)
'Determine the VM Identifier based on the vmfile location
VMFolder = fso.GetparentFoldername(vmfile)
set VMFolderObject = fso.Getfolder (VMFolder)
VMIdentifier = VMFolderObject.name
ZipFile = DefaultBackupPath & VMIdentifier & "-" & ISO_DateTime(now, 0, true) & ".zip"
'Determine the location where the temporary backup files will be saved
BackupPath = fso.GetParentFolderName(ZipFile) & "\" & VMIdentifier
way = "a"
ElseIf args.Count=2 Then 'We are in the automatic mode with 2 Arguments: VM and backup location
vmfile = args(0)
'Determine the VM Identifier based on the vmfile location
VMFolder = fso.GetparentFoldername(vmfile)
set VMFolderObject = fso.Getfolder (VMFolder)
VMIdentifier = VMFolderObject.name
ZipFile = args(1)
'Determine the location where the temporary backup files will be saved
BackupPath = fso.GetParentFolderName(ZipFile) & "\" & VMIdentifier
'Create the backuppath folder if it does not exist
If Not fso.FolderExists(BackupPath) Then
newfolder = fso.CreateFolder (BackupPath)
End If
way = "a"
Else 'There are more than two arguments provided: Error
Setup_Mail_System ("")
Error_Encountered Build_Message("InvalidArguementsMessage"), true
End If

Setup_Mail_System (VMIdentifier)

'Before doing anything else check if there is enough disk space to just copy the VM files
VMSize = round(VMFolderObject.size / OneGB, 2)
BackupDrive = fso.GetDriveName(zipfile)
Set BackupDriveObject = fso.GetDrive(BackupDrive)
BackupDriveFreeSpace = round(BackupDriveObject.availablespace / OneGB, 2)
'Don't continue if not enough space
if VMSize >= BackupDriveFreeSpace then
Error_Encountered Build_Message("InsufficientDriveSpaceErrorMessage"),true
end if

'Adding the remote server connection info if necessary
If remote_server = true Then
cp.hostname = remote_host
cp.username = remote_user
cp.password = remote_pass
cp.port = remote_port
End If

'Connect to the server
Err.clear
connected_s = False
For tries_srv = 1 To ServerConnectMaxTries
server.Connect cp
If Err.number = 0 Then
connected_s = True
Exit For
End If
WScript.Sleep ServerConnectTryInterval * OneSecond
Next
'Check for server connection errors
If Not connected_s Then
Error_Encountered Build_Message("NoServerConnectionErrorMessage"), true
End If

'Connect to the virtual machine
Err.clear
connected_m = False
For tries_vm = 1 To VMConnectMaxTries
thevm.Connect cp, vmfile
If Err.number = 0 Then
connected_m = True
Exit For
End If
WScript.Sleep VMConnectTryInterval * OneSecond
Next
'Check for VM connection errors
If Not connected_m Then
Error_Encountered Build_Message("NoVMConnectionErrorMessage"), true
End If

'Used for reporting time of operations
VMShutdownStart = now

'Get the ExecutionState of the vm to know if it must be started after backup complete
ExecutionState = thevm.ExecutionState
if ExecutionState = vmExecutionState_On then
VMWasOn = true 'It must be powered on after backup
elseIf ExecutionState = vmExecutionState_Off then
VMWasOn = false 'After backup do nothing
'We have a VM state error
else
Error_Encountered Build_Message("VMStateErrorMessage"), true
end If

'Get the approximate number of seconds from the start of VMWare Tools inside the vm.
HeartBeat = thevm.Heartbeat
if VMWasOn = true then
'VM without VMWare Tools can only be backed up if it was off.
'If no heartbeat then vmwaretools are not installed or sopmething is wrong.
if HeartBeat < 1 then
Error_Encountered Build_Message("VMWareToolsErrorMessage"), true
end if
end if

'Shut down the VM
getoff = thevm.stop(vmPowerOpMode_Soft)
VMIsOff = False
For tries_off = 1 To VMStopMaxTries
PowerState = thevm.ExecutionState
If PowerState = vmExecutionState_Off Then
VMIsOff = True
Exit For
End If
WScript.Sleep VMStopTryInterval * OneSecond
Next
'Check for VM shutdown errors
If Not VMIsOff Then
Error_Encountered Build_Message("VMShutdownErrorMessage"), true
end if

'Machine is shut down and can be copied
If remote_server = true Then
vmfolder = remote_share & "\" & VMIdentifier
End If
copyVM = fso.CopyFolder(vmfolder,BackupPath) 'checked
'Machine copied!

'If the VM was originally on then turn it back on now that copying is done
if VMWasOn = true then
geton = thevm.start(vmPowerOpMode_Soft)
'Wait until the heartbeat becomes more than 300
VMIsOn = False
For tries_on = 1 To VMStartMaxTries
Heartbeat = thevm.Heartbeat
If HeartBeat > VMStartedHeartbeat Then
VMIsOn = True
Exit For
End If
WScript.Sleep VMStartTryInterval * OneSecond
Next
If Not VMIsOn Then
'Check for VM Startup errors
Error_Encountered Build_Message("VMStartupErrorMessage"), false
end if
end if

'Used for reporting time of operations
VMRestarted = now

'Create the zip command
ZipCommand = chr(34) & seven_zip_reg & "\7z.exe" & chr(34) & " a -tzip " & chr(34) & ZipFile & chr(34) & " " & chr(34) & BackupPath & "\*" & chr(34) & seven_zip_switch
'Create the archive
CreateArchive = wshshell.Run(ZipCommand,0,true)
'Check for archive creation errors
if CreateArchive > 0 then
Error_Encountered Build_Message("ArchiveCreationErrorMessage"), true
end if

'Check if the zip file is the minumum expected size (no better way to check if the zip operation ran out of disk space but was successfull)
set ZipFileObject = fso.getfile(ZipFile)
ZipFileSize = round(ZipFileObject.size / OneGB, 2)
if ZipFileSize <= MinFileSize then
Error_Encountered Build_Message("ZipFileSizeErrorMessage"), true
end if

'Delete the temporary backup folder
deltmp = fso.deleteFolder(BackupPath)
WScript.Sleep 2 * OneSecond

'if enabled, delete backups not needed any more
if CleanUpBackupFiles then
Delete_Old_Backup_Files VMIdentifier, fso.GetParentFolderName(ZipFile)
end if

'Used for reporting time of operations
ArchiveCreated = now

'Calculate statistics
BackupDriveFreeSpace = round(BackupDriveObject.availablespace / OneGB, 2) 'Need to check again after operation
TimeVMOff = DateDiff("n",VMShutdownStart,VMRestarted)
TimeCompressing = DateDiff("n",VMRestarted,ArchiveCreated)
TimeTotal = TimeVMOff + TimeCompressing
TimeArchiveCreated = ISO_DateTime(ArchiveCreated, 2, false)
ArchiveCreated = ISO_DateTime(ArchiveCreated, 0, false)
TimeVMShutdownStart = ISO_DateTime(VMShutdownStart, 2, false)
VMShutdownStart = ISO_DateTime(VMShutdownStart, 0, false)
TimeVMRestarted = ISO_DateTime(VMRestarted, 2, false)
VMRestarted = ISO_DateTime(VMRestarted, 0, false)

'Build the FreeDiskSpace warning message if necessary.
if ((vmsize + zipfilesize) * (FreeDiskSpaceCriticalThreshold / 100)) >= BackupDriveFreeSpace then
DiskSpaceMessage = Build_Message("FreeDiskSpaceCritical")
elseif ((vmsize + zipfilesize) * (FreeDiskSpaceWarningThreshold / 100)) >= BackupDriveFreeSpace then
DiskSpaceMessage = Build_Message("FreeDiskSpaceWarning")
else
DiskSpaceMessage = ""
End If

'Generate and send the success message
Success_Message = Build_Message("SuccessMessage")
if DiskSpaceMessage "" then
Success_Message = DiskSpaceMessage & vbcrlf & vbcrlf & Success_Message & vbcrlf & vbcrlf & DiskSpaceMessage
end if
wshShell.LogEvent 0, Success_Message
mailing.TextBody = Success_Message
mailing.Subject = DefaultMailSubject & "Complete"
mailing.Configuration.Fields.Update
mailing.Send
if way = "i" Then
Cheer = msgBox(Success_Message, vbExclamation, DefaultMailSubject)
end if

Destroy_Objects

WScript.Quit
[/code]


Just a quick comment to "destroy_objects":

VMware objects should be destroyed right after checking of the heartbeat after the VM is online again, as I did it.

If you don't do it, you can't comfortably work with that VM while the script is running (and it takes its time).

E.g. it will not be possible to power it on again if you shut down it...

SirShagg,

I see you are a programmer... A question: is it generally possible to pack this baby into an executable?

SirShagg,

I see you are a programmer... A question: is it
generally possible to pack this baby into an
executable?


I'm actually a lazy admin just like you. I do however have quite a bit of programming background and experience, albeit many years ago.

I can't say for certain, but I've never heard of vbscript being compiled into an EXE. It could certainly be ported to another language (Visual basic for example) that could be compiled. Just curious though - why would you want to do that?

Just a quick comment to "destroy_objects":

VMware objects should be destroyed right after
checking of the heartbeat after the VM is online
again, as I did it.

If you don't do it, you can't comfortably work with
that VM while the script is running (and it takes its
time).

E.g. it will not be possible to power it on again if
you shut down it...


I don't disagree that this would be the ideal time to destroy the objects. I decided to make it into a sub because previously the script could be ended without destroying the objects. Since I was making the sub I figured I'd also destroy the rest of the objects that were used. Since I was still using the file and folder objects I waited till the end of the script to call the destroy_objects sub. It would be simple to just copy and paste the three lines that destroy the VM objects to the location you describe (I'd leave them in the sub too).

I'm not entirely convinced th at it's necessary though. I was under the impression that the reason for destroying the objects as essentially to release the resources (memory). Can you point me to any references about not destroying the objects immediately making the VM run funny. I checked the API documentation and couldn't see where it stated that the objects needed to be destroyed at a particular time, or even that they need to be destroyed at all. In fact their sample scripts don't even destroy the objects.

I tested shut down/restart, pause/unpause, all kinds of work in the VM while the zip operation was running (and the connections were not destroyed yet) without any issues.

High @All
First - Great work this script - so i take it some days ago and port it to german. (so sorry for my english ;-)
I added also some functions like
- suspend with hard-mode when vmtools not running (i have some vms, where it is not critical when no clear shutdown occurs)

Now im here to present my script and i see the great work of SirShagg.
I will look at this and adopt some things to my script.

I have my script published in my forum at http://www.admins-tipps.de/option,com_joomlaboard/Itemid,221/func,showcat/catid,509.htm for disscussion and development. The actual version is also at http://vmware-forum.de/viewtopic.php?t=7291&sid=5b285633feced1e097ba16301dac212c (while is it documented almost in german i think there is the better place)

my next planning is to use shadowcopy:

Const VOLUME = "F:\"
Const CONTEXT = "ClientAccessible"

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "
" & strComputer & "\root\cimv2")

Set objShadowStorage = objWMIService.Get("Win32_ShadowCopy")
errResult = objShadowStorage.Create(VOLUME, CONTEXT, strShadowID)

Take a shadowcopy is not the problem, but how to copy the files from this snapshot??

and backup all VMs of a server:

VMs = server.RegisteredVmNames
For Each vmName In VMs
'call backup
Next

Greetings from Potsdam/Germany
Stefan


Hello Stefan,

Grüße aus Hessen ;)

my next planning is to use shadowcopy

I wouldn't implement the shadow copy option: many of us are running their VMware hosts on Windows 2000 Servers where there is no shadow copy function.

Even more of us are running their hosts on Linux: we can't use the shadow copying there, also.

use suspend to backup (configurable, why not suspend?)

Time difference between suspend and shut down isn't as high as you think. Anyway it's downtime, right?

Also, it should be said: if you are running the native server applications, especially Domain Controllers or SQL servers, never do a suspending of them.

[offtopic in German]

Wenn du das machst, kriegt du Probleme ohne Ende.

[/offtopic in German]

Regards
Alex

I tested shut down/restart, pause/unpause, all kinds of work in the VM while the zip operation was running (and the connections were not destroyed yet) without any issues.

Sorry, can't confirm that.

While the connection is on; if you shut down the VM to which the API is connected, you'll never get it on again. It can be only done after the script is ready / the connection is off.

The VM process gets its ProcID while running; after shut down is that ProcID is still in the memory. VMware tries to reuse the same ProcID, bit it doesn't work.

Please test it once more.

Hello Alex,

I wouldn't implement the shadow copy option: many of
us are running their VMware hosts on Windows 2000
Servers where there is no shadow copy function.

ya i agree, i just thought it would reduce the downtime.

Time difference between suspend and shut down isn't
as high as you think. Anyway it's downtime, right?

Also, it should be said: if you are running the
native server applications, especially Domain
Controllers or SQL servers, never do a suspending of
them.


i agree again ;-). But i have to backup min. 3VMs, some of them >20Gig. Normally i backup to a NAS or Samba server over a 100Mbit network which takes about 40min for copying 20Gig. So i have to do a local copy or a shadow copy first to reduce downtime.

Alex

hey guys quick question/concern... the backup script has been working fine on one of my servers for the last week but last nights backup on one of my sbs servers did not go well...

what happened was the script runs at 12:45AM and it tried to shutdown the server but it hung on shutdown thus not shutting down... this morning users in that office could not login since the sbs server was down... i know that there already is a heartbeat that waitys for the server to shutdown, but can that haartbeat extended? or can it force the server to shutdown? when i connected to the base machine this mornning (after recieving 10 phone messages from angry users lol) i could see the VM SBS server on a grey screen with no logos... so i had to manually down the server and bring it back up... when i checked the event viewer on the base machine it said
"The Backup Script for VMware Server couldn't shut down the virtual machine D:\vmware\VMware\winNetBusiness.vmx.
in a reasonable time.
Please check it's state."

is there anyway to avoid this in the future???? i couldnt get it to email me since the sbs server is the exchange server...


side note.... did n e 1 get the shadow copy one working? just curious to know since all my base machines run on w2k3 and that would be somthing cool to test out!


Hello Stefan,

Grüße aus Hessen ;)

my next planning is to use shadowcopy

I wouldn't implement the shadow copy option: many of
us are running their VMware hosts on Windows 2000
Servers where there is no shadow copy function.

Even more of us are running their hosts on Linux: we
can't use the shadow copying there, also.


i use w2k3 as host - my live system will be a w2k3 enterprise r2 because with the new licencing model of MS, with this OS you can use 4 w2k3 servers in a vm without additional licences (see http://www.microsoft.com/germany/serverlizenzierung/produkte/windowsserver2003/neuerungen_r2.mspx sorry in german)

so are shadowcopys an interesting option


use suspend to backup (configurable, why not
suspend?)

Time difference between suspend and shut down isn't
as high as you think. Anyway it's downtime, right?

Also, it should be said: if you are running the
native server applications, especially Domain
Controllers or SQL servers, never do a suspending of
them.

i agree absolutly - this servers must cleanly shutdown with vmtools

but i have some vms wich are running without vmtools, and where is it not critical to press the powerbutton ;-)

It's certainly possible that someone will want to modify the script in a way that it many others would not want to, or couldn't use it. I'm sure there are many people who have made mods to the script and kept them private for one reason or another. It's good to know the downside of making those changes, but so long as it works for YOU then why not.

That being said: I thought I read somewhere (possibly this thread) that when you do this type of backup with the suspend option a restore must be done on the exact same hardware. Is this correct?

hey guys quick question/concern... the backup script
has been working fine on one of my servers for the
last week but last nights backup on one of my sbs
servers did not go well...

what happened was the script runs at 12:45AM and it
tried to shutdown the server but it hung on shutdown
thus not shutting down... this morning users in that
office could not login since the sbs server was
down... i know that there already is a heartbeat that
waitys for the server to shutdown, but can that
haartbeat extended? or can it force the server to
shutdown? when i connected to the base machine this
mornning (after recieving 10 phone messages from
angry users lol) i could see the VM SBS server on a
grey screen with no logos... so i had to manually
down the server and bring it back up... when i
checked the event viewer on the base machine it said

"The Backup Script for VMware Server couldn't shut
down the virtual machine
D:\vmware\VMware\winNetBusiness.vmx.
in a reasonable time.
lease check it's state."

is there anyway to avoid this in the future???? i
couldnt get it to email me since the sbs server is
the exchange server...

side note.... did n e 1 get the shadow copy one
working? just curious to know since all my base
machines run on w2k3 and that would be somthing cool
to test out!


Heartbeat isn't used for the shutdown. The command is sent to shutdown and then the script keeps checking to see if the VM state to see if it did indeed shut down. In my version of the script i made the frequency and number of checks user defined variables.
code
VMStopMaxTries = 10 'Number of attempts to stop the VM
VMStopTryInterval = 60 'Seconds between attempts to stop the VM
[/code]
Otherwise you need to go into the code for the server shutdown and adjust the upper bounds on the for loop and the sleep value at the end of the for loop.

I sounds however like the server hung on shutdown, which if that was the case then no amount of waiting would have helped. My guess is that it's possible to forcibly shutdown, but if implemented this would need to be done very carefully. Will need to look into it.

That being said: I thought I read somewhere
(possibly this thread) that when you do this type of
backup with the suspend option a restore must be done
on the exact same hardware. Is this correct?

this is an argument against the suspend - i will test it tomorow

Here is where I got that impression (second post):
http://www.vmware.com/community/thread.jspa?messageID=407181&#407181

Also see the second post by KevinG here:
http://www.vmware.com/community/thread.jspa?messageID=434750&#434750

Message was edited by:
SirShagg

thx let me know what i can do in future to prevent this... if its currently set to 10 times i guess thats good enough? or should i change that setting?

What you described sounds like the server hung on shutdown (it was still not shutdown when you got to it). In this case no amount of waiting would have helped.

I suppose the quick solution would be to change the stop parameter from 2 to 3:
code
getoff = thevm.stop(3)
[/code]

1 (vmPowerOpMode_Hard) tells the VM to to simply power off (like pulling the power plug)
2 (vmPowerOpMode_Soft) tells the VM to shutdown gracefully (shutdown the OS, etc)
3 (vmPowerOpMode_TrySoft) tells the VM to try 2, but if that fails do 1.

I must say that I would be EXTREMELY hesitant to simply change this on one of my machines. I'd probably want to do some more checking. Just off the top of my head maybe this (note: this is based on my code. I'm sorry but one of the reason i rewrote is that i had a hard time reading the original code):

code
'Try to shutdown the VM nicely
getoff = thevm.stop(vmPowerOpMode_Soft)
VMIsOff = False
For tries_off = 1 To VMStopMaxTries
PowerState = thevm.ExecutionState
If PowerState = vmExecutionState_Off Then
VMIsOff = True
Exit For
End If
WScript.Sleep VMStopTryInterval * OneSecond
Next
If Not VMIsOff and ForceShutdownIfNecessary Then
'Shut down the VM HARD if necessary
getoff = thevm.stop(vmPowerOpMode_TrySoft)
VMIsOff = False
For tries_off = 1 To VMStopMaxTries
PowerState = thevm.ExecutionState
If PowerState = vmExecutionState_Off Then
VMIsOff = True
Exit For
End If
WScript.Sleep VMStopTryInterval * OneSecond
Next
'Check for VM shutdown errors
If Not VMIsOff Then
Error_Encountered Build_Message("VMShutdownErrorMessage"), true
end if
[/code]

I'm working on a better solution to the above problem but in order to test it I need to know of a good way to reliably hang a windows machine on shutdown?

Message was edited by:
SirShagg

OK - backup of suspended VM only when restore to the same VMWare Server or a VMServer with identical Hardware.

crash a windows machine - no problem ;-)

you want a bluescreen?? see http://www.winguides.com/registry/display.php/856/

Actually I want it to hang like what Louch had happen. I'm looking to find out what the VM ExecutionState gets reports as when this occurs. If it's "unknown" then i can force a hard shutdown which should hopefully work.

Although the blue screen would be interesting too. I'll have to test that as well.

thx let me know what i can do in future to prevent
this... if its currently set to 10 times i guess
thats good enough? or should i change that setting?

Ok, I think this will do the trick. I can't say for sure because idon't know how to test it.

New user defined variables
code
VMStopMaxHungChecks = 10 'If the VM didn't stop how many times should we check if it's hung
VMStopHungSeconds = 60 'Seconds VM is unresponsive to consider it hung
[/code]

New messages
code
VMShutdownHardErrorMessageLines = 4
VMShutdownHardErrorMessage1 = "The VMware Backup Script determined that the virtual machine '%\^VMIdentifier^%' was hung for more than %\^VMStopHungSeconds^% seconds and performed a hard shutdown.__"
VMShutdownHardErrorMessage2 = "This shutdown was successfull but you may want to look into why the machine hung."
VMShutdownHardErrorMessage3 = ""
VMShutdownHardErrorMessage4 = "Backup processing will continue and you should expect another message."

CriticalVMShutdownErrorMessageLines = 2
CriticalVMShutdownErrorMessage1 = "The VMware Backup Script attempted a hard shut down on the virtual machine '%\^VMIdentifier^%'.__"
CriticalVMShutdownErrorMessage2 = "This shutdown attempt failed. Please check it's state ASAP."
[/code]

This existing message was changed slightly (replace it)
code
VMShutdownErrorMessageLines = 2
VMShutdownErrorMessage1 = "The VMware Backup Script couldn't shut down the virtual machine '%\^VMIdentifier^%' in a reasonable time.__"
VMShutdownErrorMessage2 = "The machine did not appear to be hung though. Please check it's state."
[/code]

Replace the entire "shut down the VM" section with this
code
'Shut down the VM
VMIsOff = False
For tries_off = 1 To VMStopMaxTries
getoff = thevm.stop(vmPowerOpMode_Soft) 'this method has a built in 4 min timeout
PowerState = thevm.ExecutionState
If PowerState = vmExecutionState_Off Then
VMIsOff = True
Exit For
End If
WScript.Sleep VMStopTryInterval * OneSecond
Next
'Check for VM shutdown errors
If Not VMIsOff Then
'We told the vm to shut down and it did not, we need to check if the VM is hung
for Hung_check = 1 to VMStopMaxHungChecks
'This will tell us how long the vm has been unresponsive
ToolsLastActive = thevm.ToolsLastActive
'Test if vm has been unresponsive long enough to classify as hung
if ToolsLastActive < VMStopHungSeconds then
WScript.Sleep ( 1 + VMStopHungSeconds - ToolsLastActive) * OneSecond
else
'At this point we can assume the vm is hung and try a hard shutdown
For tries_off = 1 To VMStopMaxTries
getoff = thevm.stop(vmPowerOpMode_Hard) 'this method has a built in 4 min timeout
PowerState = thevm.ExecutionState
If PowerState = vmExecutionState_Off Then
VMIsOff = True
'Not really an error but want the user to know the shutdown was hard.
Error_Encountered Build_Message("VMShutdownHardErrorMessage"), false
Exit For
End If
WScript.Sleep VMStopTryInterval * OneSecond
Next
'Check for VM shutdown errors
If Not VMIsOff Then
Error_Encountered Build_Message("CriticalVMShutdownErrorMessage"), true
end if
end if
next
If Not VMIsOff Then
'The vm didn't shut down but does not appear to be hung
Error_Encountered Build_Message("VMShutdownErrorMessage"), true
end if
end if
[/code]

Very nice script, going to try it tonight :)

Am I likely to run into problems running with compression on a 200GB VM, from a time point of view?

Am I likely to run into problems running with compression on a 200GB VM, from a time point of view?

It depends on how much data your vmdk files have. For the quick compression we need powerful CPUs...

If it's "unknown" then i can force a hard shutdown which should hopefully work.

Be careful with the "unknown" state. Nobody knows what "unknown" means. If the VM's OS hangs, is the status "running", not "unknown".

If it's "unknown" then i can force a hard shutdown
which should hopefully work.

Be careful with the "unknown" state. Nobody knows
what "unknown" means. If the VM's OS hangs, is the
status "running", not "unknown".


Thats exactly why I didn't decide to use it once I looked into the problem further. The API doc indicated that ToolsLastActive should not be higher than 5 and if the guest failed this value would indicate the number of seconds since it failed. This is why I eventually decided to use this value instead.

i have there a little enhancement for remote_backup

i have replaced :

'Machine is shut down and can be copied
If remote_server = True Then
VMFolder = remote_share & "\" & VMIdentifier
End If

with:
If remote_server = true and Left(vmfolder,2) "
" Then
vmfolder = "
" & remote_host & "\" & Left(vmfolder,1) & "$" & Right(vmfolder,Len(vmfolder)-2)
End If

this converts the vmfolder-name to UNC (administrative share) if it is not a UNC-Path

now the script is a little bit more flexible - there is no fixed remote_share in config necessary
i wrote this, because my vms are distributed over a lot of drives (performance)

I made the changes to the script like you had suggessted but my server still hangs and my backup doesnt complete... what happens now is the server says "shutting down" and than my script times out... eventually the server does shutdown but that deos me no good since the backup did not complete and the server stays off till the next morning when i get in and start it back up.... as u can see this causes many problems for me... i have copied and pasted my script below that i use "including" the new changes to shutdown the machine if it "hung"

Please take a look and let me know if i have a wrong setting or somthing needs to be changed....

-------------------------------------------------------------------------------

'Define the default VM path (for interactive mode only)
DefaultVMPath = "D:\SBSVmware\" 'Need read permissions

'Define the default destination for backup files
DefaultBackupPath = "F:\backups\" 'Need write permissions

'Define cleanup options for the backup files
CleanUpBackupFiles =true 'Should the script delete old backup files for this VM upon sucessfull backup
'Set MinFileSize even if the above value is false (used to check is archive is valid)
NumberBackupsToKeep = 5 'Maximum number of backups per VM to keep. Oldest backups above this number are deleted
MinFileSize = 2 'Minimum file size (gb) for an existing backup file to be considered valid

'Define optional compression switches
seven_zip_switch = "" 'Optional switches for use with 7Zip, perhaps " -v4g" See the 7zip manual

'Define your mail settings
ReportToMail = "*****" 'Here you'll receive mail messages.
MyMailDomain = "*****" 'Your mail domain name
SMTPServer = "192.168.101.11" 'IP address or host name. Server must be able to relay mails for your address
SMTPPort = 25 '25 is standard
DefaultMailSubject = "Backups *******" 'Subject line for email message, end with ": " if used. (the script code adds to this)

'Define remote server values
remote_server = false 'Set to true if backing up VM on another machine
'The following are Only needed if the above value is true
remote_host = "192.168.0.101" 'IP address or host name
remote_port = "902" '902 is standard
remote_user = "root" 'User on the remote server who may run the VM's
remote_pass = "password" 'User's password
remote_share = "\\server\share\Virtual Machines"'User running script must have read permission

'Define other values (defaults should be fine)
ServerConnectMaxTries = 25 'Number of attempts to connect to the server
ServerConnectTryInterval = 20 'Seconds between attempts to connect to the server
VMConnectMaxTries = 25 'Number of attempts to connect to the VM
VMConnectTryInterval = 20 'Seconds between attempts to connect to the VM
VMStopMaxTries = 25 'Number of attempts to stop the VM
VMStopTryInterval = 20 'Seconds between attempts to stop the VM
VMStartMaxTries = 25 'Number of attempts to start the VM
VMStartTryInterval = 20 'Seconds between attempts to start the VM
VMStartedHeartbeat = 300 'Number of heartbeats needed to confirm the VM started
VMStopMaxHungChecks = 40 'If the VM didn't stop how many times should we check if it's hung
VMStopHungSeconds = 45 'Seconds VM is unresponsive to consider it hung

'Free Disk Space Warning values
FreeDiskSpaceCriticalThreshold = 100 'Critical message when free disk space is below this % of the vmsize + backup size
FreeDiskSpaceWarningThreshold = 120 'Warning message when free disk space is below this % of the vmsize + backup size

'Define your error messages
'Messages can have multiple lines and can include any variable used in the script.
'
'How to define messages:
'MyMessageLines = 4 'This says the message "MyMessage" has three lines (change as the # of lines changes)
'MyMessage1 = "Here is line 1" 'This is the first line of the message (numbering should start at 1)
'MyMessage2 = "" 'This is the second line of the message (inserts a blank line in the message)
'MyMessage3 = "Here is line 3__" 'This is the third line of the message (the "__" at the end indicates no line feed.
'MyMessage4 = "Here is line 4" 'This is the third line of the message
'
'NOTE: "MyMessage" is the identifier for this message
'
'
'In order insert variables into the message you must prepend them with "%\^" and end them with "^%"
'Example: the variable vmfile would be %\^vmfile^%
'
'It's possible that you could inset a variable in a message that appears before the varialble value is defined.
'If this is the case the variable will print as "", no biggie. Is shouldn't happen because it wouldn't make sense but who knows.
'Example: us %\^VMRestarted^% in the VMShutdownErrorMessage. (if we errored out shutting down how could we have restarted)
'
'In addition to the variables above you may also want to use:
'VMFile = The name of the virtuial machine file
'VMFolder = The name of the folder where the virtual machine is located
'VMIdentifier = the virtual machine identifier (the folder that the vmfile is in)
'BackupPath = The folder where backup are created
'BackupDriveFreeSpace = The amount of free space (in gb) on the backup drive
'ZipFile = The backup file that is created
'TimeVMOff = The amount of time the VM was shutdown for the operation
'TimeCompressing = The time spent compressing the backup file
'TimeTotal = The total time spent on the backup operation
'VMsize = The size (in GB) of the Virtual Machine
'ZipFileSize = The size (in GB) of the backup file
'BackupDriveFreeSpace = The amount of free space (in GB) on the backup destination
'VMShutdownStart = The date/time when the VM was shutdown
'VMRestarted = The date/time when the VM was restarted
'ArchiveCreated = The date/time when the operation was complete
'TimeVMShutdownStart = The time when the VM was shutdown
'TimeVMRestarted = The time when the VM was restarted
'TimeArchiveCreated = The time when the operation was complete

VariablesErrorMessageLines = 3
VariablesErrorMessage1 = "It appears that there are problems in the section where the variables are defined.__" 'this section
VariablesErrorMessage2 = "Most likely a '""' has been forgotten somewhere.__"
VariablesErrorMessage3 = "Please check all the values and make sure they are correct."

VCOMErrorMessageLines = 2
VCOMErrorMessage1 = "It appears that there are problems with the VCOM API.__"
VCOMErrorMessage2 = "Either it's not installed, you are running on a 64bit system, or something else is wrong with it."

No7ZipInstalledErrorMessageLines = 2
No7ZipInstalledErrorMessage1 = "The VMware Backup Script couldn't find the 7-zip Application installed on your system.__"
No7ZipInstalledErrorMessage2 = "Please visit 7zip.org to get and install it."

InvalidArguementsMessageLines = 3
InvalidArguementsMessage1 = "Incorrect Input. The directory where the Virtual Machine files are located must be provided as argument.__"
InvalidArguementsMessage2 = "If the directory name contains spaces, please add the '""' character at the beginning and at the end of the Virtual Machine's name.__"
InvalidArguementsMessage3 = "The reading of the source code of the vm-backup.vbs script may also help ;)"

InsufficientDriveSpaceErrorMessageLines = 4
InsufficientDriveSpaceErrorMessage1 = "There is not enough free space on %\^BackupPath^% to backup the virtual machine '%\^VMIdentifier^%'."
InsufficientDriveSpaceErrorMessage2 = ""
InsufficientDriveSpaceErrorMessage3 = "The VM is approximately %\^VMsize^% GB."
InsufficientDriveSpaceErrorMessage4 = "There is only %\^BackupDriveFreeSpace^% GB free space available."

NoServerConnectionErrorMessageLines = 2
NoServerConnectionErrorMessage1 = "The VMware Backup Script couldn't create an appropriate connection to the server.__"
NoServerConnectionErrorMessage2 = "Please check if all of the VMWare Services are up and running."

NoVMConnectionErrorMessageLines = 2
NoVMConnectionErrorMessage1 = "The VMware Backup Script couldn't connect to the virtual machine '%\^vmfile^%'.__"
NoVMConnectionErrorMessage2 = "Please check that the path is correct and that the virtual machine is registered on your server."

VMStateErrorMessageLines = 2
VMStateErrorMessage1 = "The VMware Backup Script couldn't get the correct state of the virtual machine '%\^VMIdentifier^%'.__"
VMStateErrorMessage2 = "Correct states are on and off only. A virtual machine with pending question, such as new SID after copying or moving also can't be backed up."

VMWareToolsErrorMessageLines = 2
VMWareToolsErrorMessage1 = "The VMware Backup Script couldn't contact the VMWare Tools on the virtual machine '%\^VMIdentifier^%'.__"
VMWareToolsErrorMessage2 = "Because of this the VM cannot be shut down correctly. Please shut down the virtual machine manually. Afterwards it can be backed up."

VMShutdownErrorMessageLines = 2
VMShutdownErrorMessage1 = "The VMware Backup Script couldn't shut down the virtual machine '%\^VMIdentifier^%' in a reasonable time.__"
VMShutdownErrorMessage2 = "The machine did not appear to be hung though. Please check it's state."
VMShutdownHardErrorMessageLines = 4
VMShutdownHardErrorMessage1 = "The VMware Backup Script determined that the virtual machine '%\^VMIdentifier^%' was hung for more than %\^VMStopHungSeconds^% seconds and performed a hard shutdown.__"
VMShutdownHardErrorMessage2 = "This shutdown was successfull but you may want to look into why the machine hung."
VMShutdownHardErrorMessage3 = ""
VMShutdownHardErrorMessage4 = "Backup processing will continue and you should expect another message."

CriticalVMShutdownErrorMessageLines = 2
CriticalVMShutdownErrorMessage1 = "The VMware Backup Script attempted a hard shut down on the virtual machine '%\^VMIdentifier^%'.__"
CriticalVMShutdownErrorMessage2 = "This shutdown attempt failed. Please check it's state ASAP."

VMStartupErrorMessageLines = 4
VMStartupErrorMessage1 = "The VMware Backup Script couldn't power on the virtual machine '%\^VMIdentifier^%' in a reasonable time.__"
VMStartupErrorMessage2 = "Maybe the machine could not start the VMWare Tools. Please check it's state and/or configuration."
VMStartupErrorMessage3 = ""
VMStartupErrorMessage4 = "Backup processing will continue and you should expect another message."

ArchiveCreationErrorMessageLines = 4
ArchiveCreationErrorMessage1 = "The VMware Backup Script couldn't create %\^ZipFile^%.__"
ArchiveCreationErrorMessage2 = "Please check if you have enough disk space on %\^BackupPath^% and run the backup script again."
ArchiveCreationErrorMessage3 = ""
ArchiveCreationErrorMessage4 = "Note: The uncompressed virtual machine files were NOT deleted from %\^BackupPath^%."

ZipFileSizeErrorMessageLines = 7
ZipFileSizeErrorMessage1 = "The compress operation completed successfully however the zip file is smaller than expected.__"
ZipFileSizeErrorMessage2 = "Please check that all files were compressed and exist in %\^ZipFile^%.__"
ZipFileSizeErrorMessage3 = "Also check that there is enough disk space on %\^BackupPath^%."
ZipFileSizeErrorMessage4 = ""
ZipFileSizeErrorMessage5 = "The zip file is approximately %\^ZipFileSize^% GB."
ZipFileSizeErrorMessage6 = "The zip file was expected to be over %\^MinFileSize^% GB."
ZipFileSizeErrorMessage7 = "Note: The uncompressed virtual machine files were NOT deleted from %\^BackupPath^%."

FreeDiskSpaceCriticalLines = 1
FreeDiskSpaceCritical1 = "*** THERE IS NOT ENOUGH FREE DISK SPACE TO BACKUP AGAIN! ***"

FreeDiskSpaceWarningLines = 1
FreeDiskSpaceWarning1 = "*** There may not be enough free disk space to backup again. ***"

SuccessMessageLines = 13
SuccessMessage1 = "The VMware Backup Script backed up the virtual machine '%\^VMIdentifier^%' successfully."
SuccessMessage2 = ""
SuccessMessage3 = "Backup saved as %\^ZipFile^%."
SuccessMessage4 = "VM was offline %\^TimeVMOff^% minutes between %\^TimeVMShutdownStart^% and %\^TimeVMRestarted^%."
SuccessMessage5 = "The compress operation took %\^TimeCompressing^% minutes."
SuccessMessage6 = ""
SuccessMessage7 = "The VM is approximately %\^VMsize^% GB."
SuccessMessage8 = "The zip file is approximately %\^ZipFileSize^% GB."
SuccessMessage9 = "There is approximately %\^BackupDriveFreeSpace^% GB free on the backup location."
SuccessMessage10 = ""
SuccessMessage11 = "Total run time was %\^TimeTotal^% minutes."
SuccessMessage12 = "Start Time: %\^VMShutdownStart^%."
SuccessMessage13 = "End Time: %\^ArchiveCreated^%."

'***********************************************************************************************************************************
'No need to touch anything after this point
'***********************************************************************************************************************************
Const vmExecutionState_On = 1
Const vmExecutionState_Off = 2
Const vmExecutionState_Suspended = 3
Const vmExecutionState_Stuck = 4
Const vmExecutionState_Unknown = 5
Const vmPowerOpMode_Hard = 1
Const vmPowerOpMode_Soft = 2
Const vmPowerOpMode_TrySoft = 3

Const OneMB = 1048576
Const OneGB = 1073741824
Const OneSecond = 1000

'Create objects
Set mailing = CreateObject("CDO.Message")
Set wshNet = CreateObject("WScript.Network")
Set wshShell = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")

'Uncomment to test messages
'Setup_Mail_System ("")
'Error_Encountered Build_Message("VariablesErrorMessage"),true

'Check for errors (decent chance of a typo in all those messages above)
If Err.number 0 then
Setup_Mail_System ("")
Error_Encountered Build_Message("VariablesErrorMessage"),true
end if

'Create VMCOM objects
Set cp = CreateObject("VmCOM.VmConnectParams")
Set server = CreateObject("VmCOM.VmServerCtl")
Set thevm = CreateObject("VmCOM.VmCtl")

'Check for VCOM errors
If Err.number 0 then
Setup_Mail_System ("")
Error_Encountered Build_Message("VCOMErrorMessage"),true
end if

Function Build_Message (byval Message)
'*******************************************************************************************
'Builds a message to be displayed to the user. It Takes a single string parameter "x".
'It looks for variables defined as X + "Lines" and X + <number>.
'X + "lines" is the number of lines for the message and each X + <number> is a message line.
'It loops through all the message lines to build the message. Message lines can contain
'variables which must be preceeded by "%\^" and followed by "^%". The variables will be
'decoded and and their current value will be inserted into the message.
'*******************************************************************************************
On Error Resume Next

'Initialize temp value
TempMessage = ""
'Get number of lines in message
j = eval(cstr(Message) + "Lines")
'Loop through all the message lines
for i = 1 to j
'Get a message line
Junk = eval(cstr(Message) + cstr(i))
'Handle line feeds
if right (Junk, 2) = "__" then
Junk = left (Junk, len (Junk) -2) & " "
else
Junk = Junk & vbcrlf
end if
'Get position of variable in message line
pos1 = instr (1, Junk, "%^")
Pos2 = instr (1, Junk, "^%")
'Process all variables in the message line
while pos1 + pos2 > 0
'Get the variable name
var = mid(Junk, pos1 +2, (pos2 - pos1) - 2)
'replace the varialbe placeholder with the variable name
Junk = replace(Junk, "%\^" & var & "^%", eval(var))
'Check for more variables in the line
pos1 = instr (1, Junk, "%^")
Pos2 = instr (1, Junk, "^%")
wend
'Add the message line to the complete message
TempMessage = TempMessage & Junk
next
'Return the complete message
Build_Message = TempMessage

end function

Sub Delete_Old_Backup_Files (byval VMName, byval BackupFolder)
'*******************************************************************************************
'Deletes older backup files to conserve disk space.
'*******************************************************************************************
On Error Resume Next

set FSO = createobject("scripting.filesystemobject")
set Folder = FSO.getfolder(BackupFolder)
set Files = Folder.Files
Dim NFileArray ()
Dim MFileArray ()

'Initialize values now that we can
RealFileCount = Folder.Files.Count
redim NFileArray (RealFilecount)
redim MFileArray (RealFileCount)

'Fetch the list of files
MyFileCount = 0
for each file in Files
'Only files matching the VM identifier count
if strcomp (left(file.name, (len(VMName)+1)), VMName & "-",1) = 0 then
'Only files bigger than "x" GB in size count
if file.size >= (MinFileSize * OneGB) then
MyFileCount = MyFileCount + 1
NFileArray(MyFileCount) = file
MFileArray(MyFileCount) = File.DateLastModified
end if
end if
next

'No sense doing anything else if less files then max allowed
if MyFileCount > NumberBackupsToKeep then
'Sort by modified date
for i = 1 to MyFileCount
for j = (i + 1) to MyFileCount
if MFileArray(i) < MFileArray(j) then
NBuffer = NFileArray(j)
MBuffer = MFileArray(j)
NFileArray(j) = NFileArray(i)
MFileArray(j) = MFileArray(i)
NFileArray(i) = NBuffer
MFileArray(i) = MBuffer
end if
next
next
'Delete part
for n = NumberBackupsToKeep + 1 to MyFileCount 'Array position zero is blank
Set Deletefile = FSO.getfile(NfileArray(n))
Deletefile.delete true
next
end if

'Destroy objects
set FSO = nothing
set Folder = nothing
set Files = nothing

end sub

Sub Setup_Mail_System (byval VMName)
'*******************************************************************************************
'Setup the mail system. Made into becasue I wanted to send notification if the arguements
'passed to the script were bad.
'*******************************************************************************************
On Error Resume Next

mailing.To = ReportToMail
if VMName is not null then
mailing.from = "VM-" & ucase(VMName) & "@" & MyMailDomain
else
mailing.from = "VM-**Unknown**" & "@" & MyMailDomain
end if
mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = SMTPServer
mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = SMTPPort

end sub

sub Error_Encountered (byval ErrorMessage, byval StopError)
'*******************************************************************************************
' Write a message to the application log, send email (& messagebox if interactive) and quit
'*******************************************************************************************
On Error Resume Next

wshShell.LogEvent 1, ErrorMessage
if StopError then
mailing.Subject = DefaultMailSubject & "Critical Error"
else
mailing.Subject = DefaultMailSubject & "Warning"
end if
mailing.TextBody = ErrorMessage
mailing.Configuration.Fields.Update
mailing.Send
If way="i" Then
Cry = msgBox(ErrorMessage,vbCritical,DefaultMailSubject)
End If
if StopError then
Destroy_Objects
WScript.Quit
end if

end sub

Function ISO_DateTime (byval dt, byval dttype, byval NoSpecialChars)
'*******************************************************************************************
'Converts dates/Times to ISO format
'First parameter is the date/time
'Second is the type of conversion: 1=Date Only, 2=Time only, anything else does both
'Third determines if the ":" can appear in the time
'*******************************************************************************************
On Error Resume Next

dim y: y=year(dt)
dim m: m=month(dt)
dim d: d=day(dt)
dim h: h=hour(dt)
dim n: n=minute(dt)
dim s: s=second(dt)

if m < 10 then m="0" & m
if d < 10 then d="0" & d
if h < 10 then h="0" & h
if n < 10 then n="0" & n
if s < 10 then s="0" & s

'Handle Date
TheDate = y & "-" & m & "-" & d
'Handle Time
if NoSpecialChars then
TheTime = h & n & s
else
TheTime = h & ":" & n & ":" & s
end if
'Combine for Date/Time
TheDateTime = TheDate & "T" & TheTime

'Return whichever value the user wanted
if dttype = 1 then
ISO_DateTime = TheDate
elseif dttype = 2 then
ISO_DateTime = TheTime
else
ISO_DateTime = TheDateTime
end if

end Function

sub Destroy_Objects ()
'*******************************************************************************************
'Destroy the various objects we created. Made into a sub because the script quits from
'more then one place (if errors).
'*******************************************************************************************
On Error Resume Next

'Destroy objects
Set mailing = nothing
Set wshNet = nothing
Set wshShell = nothing
Set fso = nothing
Set thevm = Nothing
Set server = Nothing
Set cp = Nothing
set VMFolderObject = nothing
set BackupDriveObject = nothing
set ZipFileObject = nothing
set args = nothing
WScript.Sleep 2 * OneSecond

end sub

'Check if 7zip is installed
Err.clear
seven_zip_reg = "C:\Program Files\7-zip"
'Check for errors
If Err.number 0 then
Setup_Mail_System ("")
Error_Encountered Build_Message("No7ZipInstalledErrorMessage"),true
end if

'Get the name of the VM delivered by the script argument. Number of arguements must be between 0-2
'If none, then prompt the user for values
'If one, then the user only specified the VM to backup and use default backup file
'If two, then the user wants to define the VM to backup and backup file manually
'If three or more than there is something wrong
Set args = WScript.Arguments
if args.count=0 then 'We are in the interactive mode, way = "i(nteractive)"
'Prompt for the name of the vmfile
vmfile = inputBox("Please enter the full path to the .vmx file of the virtual machine you want to backup:",DefaultMailSubject,DefaultVMPath)
'Quit if cancel
if vmfile = "" then
Destroy_Objects
WScript.Quit
end if
'Determine the VM Identifier based on the vmfile location
VMFolder = fso.GetparentFoldername(vmfile)
set VMFolderObject = fso.Getfolder (VMFolder)
VMIdentifier = VMFolderObject.name
'prompt for the name of the zipfile
TempValue = DefaultBackupPath & VMIdentifier & "-" & ISO_DateTime(now, 0, true) & ".zip"
ZipFile = inputBox("Now, please enter the full path to the .zip file the script will create:",DefaultMailSubject,TempValue)
'Quit if cancel
if ZipFile = "" then
Destroy_Objects
WScript.Quit
end if
'Determine the location where the temporary backup files will be saved
BackupPath = fso.GetParentFolderName(ZipFile) & "\" & VMIdentifier
way = "i"
elseIf args.Count=1 Then 'We are in the mode with predefined vm by parameter, way = "a(utomatic)"
vmfile = args(0)
'Determine the VM Identifier based on the vmfile location
VMFolder = fso.GetparentFoldername(vmfile)
set VMFolderObject = fso.Getfolder (VMFolder)
VMIdentifier = VMFolderObject.name
ZipFile = DefaultBackupPath & VMIdentifier & "-" & ISO_DateTime(now, 0, true) & ".zip"
'Determine the location where the temporary backup files will be saved
BackupPath = fso.GetParentFolderName(ZipFile) & "\" & VMIdentifier
way = "a"
ElseIf args.Count=2 Then 'We are in the automatic mode with 2 Arguments: VM and backup location
vmfile = args(0)
'Determine the VM Identifier based on the vmfile location
VMFolder = fso.GetparentFoldername(vmfile)
set VMFolderObject = fso.Getfolder (VMFolder)
VMIdentifier = VMFolderObject.name
ZipFile = args(1)
'Determine the location where the temporary backup files will be saved
BackupPath = fso.GetParentFolderName(ZipFile) & "\" & VMIdentifier
'Create the backuppath folder if it does not exist
If Not fso.FolderExists(BackupPath) Then
newfolder = fso.CreateFolder (BackupPath)
End If
way = "a"
Else 'There are more than two arguments provided: Error
Setup_Mail_System ("")
Error_Encountered Build_Message("InvalidArguementsMessage"), true
End If

Setup_Mail_System (VMIdentifier)

'Before doing anything else check if there is enough disk space to just copy the VM files
VMSize = round(VMFolderObject.size / OneGB, 2)
BackupDrive = fso.GetDriveName(zipfile)
Set BackupDriveObject = fso.GetDrive(BackupDrive)
BackupDriveFreeSpace = round(BackupDriveObject.availablespace / OneGB, 2)
'Don't continue if not enough space
if VMSize >= BackupDriveFreeSpace then
Error_Encountered Build_Message("InsufficientDriveSpaceErrorMessage"),true
end if

'Adding the remote server connection info if necessary
If remote_server = true Then
cp.hostname = remote_host
cp.username = remote_user
cp.password = remote_pass
cp.port = remote_port
End If

'Connect to the server
Err.clear
connected_s = False
For tries_srv = 1 To ServerConnectMaxTries
server.Connect cp
If Err.number = 0 Then
connected_s = True
Exit For
End If
WScript.Sleep ServerConnectTryInterval * OneSecond
Next
'Check for server connection errors
If Not connected_s Then
Error_Encountered Build_Message("NoServerConnectionErrorMessage"), true
End If

'Connect to the virtual machine
Err.clear
connected_m = False
For tries_vm = 1 To VMConnectMaxTries
thevm.Connect cp, vmfile
If Err.number = 0 Then
connected_m = True
Exit For
End If
WScript.Sleep VMConnectTryInterval * OneSecond
Next
'Check for VM connection errors
If Not connected_m Then
Error_Encountered Build_Message("NoVMConnectionErrorMessage"), true
End If

'Used for reporting time of operations
VMShutdownStart = now

'Get the ExecutionState of the vm to know if it must be started after backup complete
ExecutionState = thevm.ExecutionState
if ExecutionState = vmExecutionState_On then
VMWasOn = true 'It must be powered on after backup
elseIf ExecutionState = vmExecutionState_Off then
VMWasOn = false 'After backup do nothing
'We have a VM state error
else
Error_Encountered Build_Message("VMStateErrorMessage"), true
end If

'Get the approximate number of seconds from the start of VMWare Tools inside the vm.
HeartBeat = thevm.Heartbeat
if VMWasOn = true then
'VM without VMWare Tools can only be backed up if it was off.
'If no heartbeat then vmwaretools are not installed or sopmething is wrong.
if HeartBeat < 1 then
Error_Encountered Build_Message("VMWareToolsErrorMessage"), true
end if
end if

'Shut down the VM
VMIsOff = False
For tries_off = 1 To VMStopMaxTries
getoff = thevm.stop(vmPowerOpMode_Soft) 'this method has a built in 4 min timeout
PowerState = thevm.ExecutionState
If PowerState = vmExecutionState_Off Then
VMIsOff = True
Exit For
End If
WScript.Sleep VMStopTryInterval * OneSecond
Next
'Check for VM shutdown errors
If Not VMIsOff Then
'We told the vm to shut down and it did not, we need to check if the VM is hung
for Hung_check = 1 to VMStopMaxHungChecks
'This will tell us how long the vm has been unresponsive
ToolsLastActive = thevm.ToolsLastActive
'Test if vm has been unresponsive long enough to classify as hung
if ToolsLastActive < VMStopHungSeconds then
WScript.Sleep ( 1 + VMStopHungSeconds - ToolsLastActive) * OneSecond
else
'At this point we can assume the vm is hung and try a hard shutdown
For tries_off = 1 To VMStopMaxTries
getoff = thevm.stop(vmPowerOpMode_Hard) 'this method has a built in 4 min timeout
PowerState = thevm.ExecutionState
If PowerState = vmExecutionState_Off Then
VMIsOff = True
'Not really an error but want the user to know the shutdown was hard.
Error_Encountered Build_Message("VMShutdownHardErrorMessage"), false
Exit For
End If
WScript.Sleep VMStopTryInterval * OneSecond
Next
'Check for VM shutdown errors
If Not VMIsOff Then
Error_Encountered Build_Message("CriticalVMShutdownErrorMessage"), true
end if
end if
next
If Not VMIsOff Then
'The vm didn't shut down but does not appear to be hung
Error_Encountered Build_Message("VMShutdownErrorMessage"), true
end if
end if

'Used for reporting time of operations
VMRestarted = now

'Create the zip command
ZipCommand = chr(34) & seven_zip_reg & "\7z.exe" & chr(34) & " a -tzip " & chr(34) & ZipFile & chr(34) & " " & chr(34) & BackupPath & "\*" & chr(34) & seven_zip_switch
'Create the archive
CreateArchive = wshshell.Run(ZipCommand,0,true)
'Check for archive creation errors
if CreateArchive > 0 then
Error_Encountered Build_Message("ArchiveCreationErrorMessage"), true
end if

'Check if the zip file is the minumum expected size (no better way to check if the zip operation ran out of disk space but was successfull)
set ZipFileObject = fso.getfile(ZipFile)
ZipFileSize = round(ZipFileObject.size / OneGB, 2)
if ZipFileSize <= MinFileSize then
Error_Encountered Build_Message("ZipFileSizeErrorMessage"), true
end if

'Delete the temporary backup folder
deltmp = fso.deleteFolder(BackupPath)
WScript.Sleep 2 * OneSecond

'if enabled, delete backups not needed any more
if CleanUpBackupFiles then
Delete_Old_Backup_Files VMIdentifier, fso.GetParentFolderName(ZipFile)
end if

'Used for reporting time of operations
ArchiveCreated = now

'Calculate statistics
BackupDriveFreeSpace = round(BackupDriveObject.availablespace / OneGB, 2) 'Need to check again after operation
TimeVMOff = DateDiff("n",VMShutdownStart,VMRestarted)
TimeCompressing = DateDiff("n",VMRestarted,ArchiveCreated)
TimeTotal = TimeVMOff + TimeCompressing
TimeArchiveCreated = ISO_DateTime(ArchiveCreated, 2, false)
ArchiveCreated = ISO_DateTime(ArchiveCreated, 0, false)
TimeVMShutdownStart = ISO_DateTime(VMShutdownStart, 2, false)
VMShutdownStart = ISO_DateTime(VMShutdownStart, 0, false)
TimeVMRestarted = ISO_DateTime(VMRestarted, 2, false)
VMRestarted = ISO_DateTime(VMRestarted, 0, false)

'Build the FreeDiskSpace warning message if necessary.
if ((vmsize + zipfilesize) * (FreeDiskSpaceCriticalThreshold / 100)) >= BackupDriveFreeSpace then
DiskSpaceMessage = Build_Message("FreeDiskSpaceCritical")
elseif ((vmsize + zipfilesize) * (FreeDiskSpaceWarningThreshold / 100)) >= BackupDriveFreeSpace then
DiskSpaceMessage = Build_Message("FreeDiskSpaceWarning")
else
DiskSpaceMessage = ""
End If

'Generate and send the success message
Success_Message = Build_Message("SuccessMessage")
if DiskSpaceMessage "" then
Success_Message = DiskSpaceMessage & vbcrlf & vbcrlf & Success_Message & vbcrlf & vbcrlf & DiskSpaceMessage
end if
wshShell.LogEvent 0, Success_Message
mailing.TextBody = Success_Message
mailing.Subject = DefaultMailSubject & "Complete"
mailing.Configuration.Fields.Update
mailing.Send
if way = "i" Then
Cheer = msgBox(Success_Message, vbExclamation, DefaultMailSubject)
end if

Destroy_Objects

WScript.Quit


It appears that you are missing a chunk of code that copies the files and restarts the VM.

search for this line:
code
'Used for reporting time of operations
[/code]

then paste this above it:
code
'Machine is shut down and can be copied
If remote_server = true Then
vmfolder = remote_share & "\" & VMIdentifier
End If
copyVM = fso.CopyFolder(vmfolder,BackupPath) 'checked
'Machine copied!

'If the VM was originally on then turn it back on now that copying is done
if VMWasOn = true then
VMIsOn = False
For tries_on = 1 To VMStartMaxTries
geton = thevm.start(vmPowerOpMode_Soft) 'this method has a built in 4 min timeout
Heartbeat = thevm.Heartbeat
'Wait until the heartbeat becomes more than 300
If HeartBeat > VMStartedHeartbeat Then
VMIsOn = True
Exit For
End If
WScript.Sleep VMStartTryInterval * OneSecond
Next
If Not VMIsOn Then
'Check for VM Startup errors
Error_Encountered Build_Message("VMStartupErrorMessage"), false
end if
end if
[/code]

Hi, love the script but having a slight issue.

Is this script meant to delete the temporary folder that is created from copying the production VM image from and what the zipped file is based on?

I run the script vm-backup.vbs d:\vmware\Server1\vm.vmx and it created the directory d:\backup\Server1 and then creates the zip file under d: \backup, but does not delete the directory d:\backup\Server1

Wonder if I am missing something or if the script doesn't do this.

Cheers.

The script IS supposed to delete the temporary folder. I've seen twice now where I'm left with the temporary folder but no files in it. All other times it's deleted the folder as well as all the files in it. To be honest I have not even tried to figure out why as this is not a big deal to me. Now if files were still left there too then I might be concerned.

Unfortunately for me for all three machines I have done, it has left the temp directory and files behind.

This is of course the script that was posted by SirShagg on the 6th December. Wonder if something was missing in that version of the script compared to the other two that were posted?

The code to delete the folder is there:

code
'Delete the temporary backup folder
deltmp = fso.deleteFolder(BackupPath)
WScript.Sleep 2 * OneSecond
[/code]

Is it possible that the files are read only? This code will probably fail if they are, but I can't see why they would be. I assume the user has rights to delete the files and folder. Could an AV program be holding onto the files? No other similiar issues.

Is your DefaultBackupPath = "D:\backups\"?

Just for testing purposes you might want to add the following at the end of the code shown above. Note: This WILL cause the script to stop untll you respond to the message, but nothing major is left in the script anyway. The values displayed might help in diagnosing the issue.

code
msgbox "'" & BackupPath & "' '" & deltemp & "'"
[/code]

p.s. There is an error in the code posted on 12/6, but it has to do with backing up remote machines and should be completely unrelated to this issue you are seeing. In this instance copying never even takes place.


Just ran one of the older versions of the script and it deletes the temporary file from the directory (it was D:\Backup).

Not too sure, might trawl through the respective code versions and find if something is missing.

Thanks for your help.

Hello,

i'm not able to backup a VM that's on a share. The VM is on a physical server called VMWARE3. The script is on a server called VMWARE2. From server VMWARE2 i can browse the share where my VM is. But when i try to run the script i get the following message:

The VMware Backup Script couldn't connect to the virtual machine '\\vmware3\Virtual Machines\Johannesburg\vm.vmx'. Please check that the path is correct and that the virtual machine is registered on your server.

What can cause this message??

Regards,
Patrick

Which version of the script are you using? The version I posted definitely had an error in handling remote servers.

But will this fix my hanging/shutting down issue?

It won't address a hung server. However, the code you posted would result in the VM being shut down and never restarted. The code to restart the server (as well as the code to copy the VM files) is missing in the code you posted.

Now if the server is actually hanging on shutdown then the "restart" code won't do you any good since the machine was never really shut down completely. If the machine actually hangs than you need to determine why. It should be unrelated to the backup script. Perhaps you have some process running on the server which gets hung up and you need a shutdown script in the VMware tools to handle the "problem" process. For example I added such a script to my servers since they run terminal services and I didn't want active sessions to just be terminated. The scripot in VMware tools shuts down TS nicely.

If the machine shuts down completely and never restarts then this will most likely fix the issue.

I've tried all version, Saxa, your's and the one from Potsdam.
The one from Potsdam keeps complaining about a not registered VM.

There is a solution on the Potsdam site: http://www.admins-tipps.de/option,com_joomlaboard/Itemid,221/func,view/id,604/catid,509.htm but i can't get it to work.

What should i do to register a remote VM?

Have you installed the vmware software on the machine where you are doing the backups from? you need at least the Vcom API's

You can download it from here:
http://www.vmware.com/download/sdk/api.html

Here is the latest version of the code which fixes the error I made in regards to backing up remote servers.
It also includes the code discussed above for (hopefully) better handling of hung servers.
One last addition is a user defined delay between copying files and zipping them.

code
'Copyleft saxa aka Alexander Kaufmann, 2006
'Butchered by SirShagg, 2006 - 2007

'By all means, completely ignore the following :)
'***********************************************************************************************************************************
'Written just for fun, total Open Source, Use it at your own risk, and whatever else don't blame me if you have problems.
'
'The script uses the VmCOM API for the virtual machine operations. You must have this installed separately if
'VMware server is not installed on the machine running this script (ie: backing up remote virtual machines)
'
'The virtual machine *must* have the VMware Tools installed, in order to backup running virtual machines.
'
'The script will work on Windows 2000 SP4 and newer. It was also successfully tested on Vista.
'
'Plese keep in mind the strangeness of the script execution on 64bit Windows - there is no VmCOM 64bit,
'so you have to run it in 32bit context. See your Windows Help for details.
'
'The script can be applied to a local host or to remote host: see the remote_server variable.
'The script *can* backup to the network share, if you have the appropriate permissions to write on it.
'
'The most important thing for remote execution: You have to share your Virtual Machines directory on the host. The user who
'runs the script (not the remote_user) must have the read permissions on that share. For Linux users: install and configure
'Samba...For Windows users: hidden shares?!
'
'For the backup jobs the script uses the command line version of 7zip. Get it on http://7zip.org/download.html.
'Just download the full install - there is also a 64 bit version available.
'
'The subdirectory where the virtual machine is located is very important for this script: it's the virtual machine's identifier.
'It will become the part of the name of the zip file.
'
'The code to delete old backup files will incorrectly delete files if one virtual machine identifier is a beginning substring
'of another. Ie: machine1 identifier = "VM10"; machine2 identifier = "VM10-1" (don't do this). Us this option at your own risk.
'

'*************************************************
'The script will do the following (simplified):
'*************************************************
'The VMware Tools inside the virtual machine receives the command to shut down the operating system. The script waits a
'set period of times and checks the state of the virtual machine. If the vm is still running then the script waits some more and
'checks again. This continues untill the VM is off or a timeout occurs (failure). As soon as the vm is off, the script
'creates a copy of the vm's folder to the backup location. After the copying is done, the vm receives the command to start
'if it was running before the operation had begun. The script then checks that the VM is up and running in much the same way it
'checked if it had been shut down. As soon as the VM is confirmed running the script starts to create a compressed archive
'from a previously copied vm directory. After the .zip file has been created, the script checks if there were any errors
'produced by 7zip and if not the copied VM files are deleted and we are left with just the zip file. Next the script checks if
'any older zip files (backups) can be deleted.
'
'The .zip archive will be named as: Virtual Machine Identifier-YYYY-MM-DD-HHMMSS.zip. The creation of the .zip file takes it's sweet
'time: on Pentium 4 (with Hyperthreading, single core) 2.8 GHz machine with 3GB RAM, the compress operation on a virtual
'machine having 2 virtual HDDs at 16 and 36 GB was about 2 hours.
'
'Throughout this process error checks are made and noted with emails sent to the administrator.

'*********************************************************************************
'You will start the script as follows (substitute your own path and file name):
'*********************************************************************************
'vm-backup.vbs "D:\Virtual Machines\Virtual Machine 1\vm.vmx" (this is interactive mode)
'
'If you want to use the script in a sheduled task, please use the following command line:
'
'wscript.exe vm-backup.vbs "D:\Virtual Machines\Virtual Machine 1\vm.vmx"
'or if you also want ot specify the backup file manually
'wscript.exe vm-backup.vbs "D:\Virtual Machines\Virtual Machine 1\vm.vmx" "D:\Backup\myvmbackup.zip"

On Error Resume Next
'***********************************************************************************************************************************
' All the values that you need to specify are conveniently located in this section.
'***********************************************************************************************************************************

'Define the default VM path (for interactive mode only)
DefaultVMPath = "D:\Virtual Machines\" 'Relative to VMware host. Need read permissions

'Define the default destination for backup files
DefaultBackupPath = "D:\backups\" 'Relative to the machine running the script, UNC is OK. Need write permissions

'Define cleanup options for the backup files
CleanUpBackupFiles = false 'Should the script delete old backup files for this VM upon sucessfull backup
'Set MinFileSize even if the above value is false (used to check is archive is valid)
NumberBackupsToKeep = 7 'Maximum number of backups per VM to keep. Oldest backups above this number are deleted
MinFileSize = 1 'Minimum file size (gb) for an existing backup file to be considered valid

'Define optional compression switches
seven_zip_switch = "" 'Optional switches for use with 7Zip, perhaps " -v4g" See the 7zip manual

'Define your mail settings
ReportToMail = "admin@mydomain.com" 'Here you'll receive mail messages.
MyMailDomain = "mydomain.com" 'Your mail domain name
SMTPServer = "smtp.mydomain.com" 'IP address or host name. Server must be able to relay mails for your address
SMTPPort = 25 '25 is standard
DefaultMailSubject = "" 'Subject line for email message, end with ": " if used. (the script code adds to this)

'Define remote server values
remote_server = True 'Set to true if backing up VM on another machine
'The following are Only needed if the above value is true
remote_host = "192.168.0.101" 'IP address or host name
remote_port = "902" '902 is standard
remote_user = "root" 'User on the remote server who may run the VM's
remote_pass = "password" 'User's password
remote_share = "\\server\share\Virtual Machines"'User running script must have read permission

'Define other values (defaults should be fine)
ServerConnectMaxTries = 10 'Number of attempts to connect to the server
ServerConnectTryInterval = 1 'Seconds between attempts to connect to the server
VMConnectMaxTries = 10 'Number of attempts to connect to the VM
VMConnectTryInterval = 1 'Seconds between attempts to connect to the VM
VMStopMaxTries = 10 'Number of attempts to stop the VM
VMStopTryInterval = 60 'Seconds between attempts to stop the VM
VMStopMaxHungChecks = 10 'If the VM didn't stop how many times should we check if it's hung
VMStopHungSeconds = 60 ' 'Seconds VM is unresponsive to consider it hung
VMStartMaxTries = 10 'Number of attempts to start the VM
VMStartTryInterval = 60 'Seconds between attempts to start the VM
VMStartedHeartbeat = 300 'Number of heartbeats needed to confirm the VM started

'Free Disk Space Warning values
FreeDiskSpaceCriticalThreshold = 100 'Critical message when free disk space is below this % of the vmsize + backup size
FreeDiskSpaceWarningThreshold = 120 'Warning message when free disk space is below this % of the vmsize + backup size

'When backing up multiple machines to the same destination you may want to delay compressing till all copying operations
'are done. This way the backed up machines are down as little as possible.
PauseBeforeCompress = 1 'Minutes to pause afer coying before compressing

'Define your error messages
'Messages can have multiple lines and can include any variable used in the script.
'
'How to define messages:
'MyMessageLines = 4 'This says the message "MyMessage" has three lines (change as the # of lines changes)
'MyMessage1 = "Here is line 1" 'This is the first line of the message (numbering should start at 1)
'MyMessage2 = "" 'This is the second line of the message (inserts a blank line in the message)
'MyMessage3 = "Here is line 3__" 'This is the third line of the message (the "__" at the end indicates no line feed.
'MyMessage4 = "Here is line 4" 'This is the third line of the message
'
'NOTE: "MyMessage" is the identifier for this message
'
'
'In order insert variables into the message you must prepend them with "%\^" and end them with "^%"
'Example: the variable vmfile would be %\^vmfile^%
'
'It's possible that you could inset a variable in a message that appears before the varialble value is defined.
'If this is the case the variable will print as "", no biggie. Is shouldn't happen because it wouldn't make sense but who knows.
'Example: us %\^VMRestarted^% in the VMShutdownErrorMessage. (if we errored out shutting down how could we have restarted)
'
'In addition to the variables above you may also want to use:
'VMFile = The name of the virtuial machine file
'VMFolder = The name of the folder where the virtual machine is located
'VMIdentifier = the virtual machine identifier (the folder that the vmfile is in)
'BackupPath = The folder where backup are created
'BackupDriveFreeSpace = The amount of free space (in gb) on the backup drive
'ZipFile = The backup file that is created
'TimeVMOff = The amount of time the VM was shutdown for the operation
'TimePaused = The amount of time paused between copying and compressing
'TimeCompressing = The time spent compressing the backup file
'TimeTotal = The total time spent on the backup operation
'VMsize = The size (in GB) of the Virtual Machine
'ZipFileSize = The size (in GB) of the backup file
'BackupDriveFreeSpace = The amount of free space (in GB) on the backup destination
'VMShutdownStart = The date/time when the VM was shutdown
'VMRestarted = The date/time when the VM was restarted
'ArchiveCreated = The date/time when the operation was complete
'TimeVMShutdownStart = The time when the VM was shutdown
'TimeVMRestarted = The time when the VM was restarted
'TimeArchiveCreated = The time when the operation was complete

VariablesErrorMessageLines = 3
VariablesErrorMessage1 = "It appears that there are problems in the section where the variables are defined.__" 'this section
VariablesErrorMessage2 = "Most likely a '""' has been forgotten somewhere.__"
VariablesErrorMessage3 = "Please check all the values and make sure they are correct."

VCOMErrorMessageLines = 2
VCOMErrorMessage1 = "It appears that there are problems with the VCOM API.__"
VCOMErrorMessage2 = "Either it's not installed, you are running on a 64bit system, or something else is wrong with it."

No7ZipInstalledErrorMessageLines = 2
No7ZipInstalledErrorMessage1 = "The VMware Backup Script couldn't find the 7-zip Application installed on your system.__"
No7ZipInstalledErrorMessage2 = "Please visit 7zip.org to get and install it."

InvalidArguementsMessageLines = 3
InvalidArguementsMessage1 = "Incorrect Input. The directory where the Virtual Machine files are located must be provided as argument.__"
InvalidArguementsMessage2 = "If the directory name contains spaces, please add the '""' character at the beginning and at the end of the Virtual Machine's name.__"
InvalidArguementsMessage3 = "The reading of the source code of the vm-backup.vbs script may also help ;)"

InsufficientDriveSpaceErrorMessageLines = 4
InsufficientDriveSpaceErrorMessage1 = "There is not enough free space on %\^BackupPath^% to backup the virtual machine '%\^VMIdentifier^%'."
InsufficientDriveSpaceErrorMessage2 = ""
InsufficientDriveSpaceErrorMessage3 = "The VM is approximately %\^VMsize^% GB."
InsufficientDriveSpaceErrorMessage4 = "There is only %\^BackupDriveFreeSpace^% GB free space available."

NoServerConnectionErrorMessageLines = 2
NoServerConnectionErrorMessage1 = "The VMware Backup Script couldn't create an appropriate connection to the server.__"
NoServerConnectionErrorMessage2 = "Please check if all of the VMWare Services are up and running."

NoVMConnectionErrorMessageLines = 2
NoVMConnectionErrorMessage1 = "The VMware Backup Script couldn't connect to the virtual machine '%\^vmfile^%'.__"
NoVMConnectionErrorMessage2 = "Please check that the path is correct and that the virtual machine is registered on your server."

VMStateErrorMessageLines = 2
VMStateErrorMessage1 = "The VMware Backup Script couldn't get the correct state of the virtual machine '%\^VMIdentifier^%'.__"
VMStateErrorMessage2 = "Correct states are on and off only. A virtual machine with pending question, such as new SID after copying or moving also can't be backed up."

VMWareToolsErrorMessageLines = 2
VMWareToolsErrorMessage1 = "The VMware Backup Script couldn't contact the VMWare Tools on the virtual machine '%\^VMIdentifier^%'.__"
VMWareToolsErrorMessage2 = "Because of this the VM cannot be shut down correctly. Please shut down the virtual machine manually. Afterwards it can be backed up."

VMShutdownHardErrorMessageLines = 4
VMShutdownHardErrorMessage1 = "The VMware Backup Script determined that the virtual machine '%\^VMIdentifier^%' was hung for more than %\^VMStopHungSeconds^% seconds and performed a hard shutdown.__"
VMShutdownHardErrorMessage2 = "This shutdown was successfull but you may want to look into why the machine hung."
VMShutdownHardErrorMessage3 = ""
VMShutdownHardErrorMessage4 = "Backup processing will continue and you should expect another message."

CriticalVMShutdownErrorMessageLines = 2
CriticalVMShutdownErrorMessage1 = "The VMware Backup Script attempted a hard shut down on the virtual machine '%\^VMIdentifier^%'.__"
CriticalVMShutdownErrorMessage2 = "This shutdown attempt failed. Please check it's state ASAP."

VMShutdownErrorMessageLines = 2
VMShutdownErrorMessage1 = "The VMware Backup Script couldn't shut down the virtual machine '%\^VMIdentifier^%' in a reasonable time.__"
VMShutdownErrorMessage2 = "The machine did not appear to be hung though. Please check it's state."

VMStartupErrorMessageLines = 4
VMStartupErrorMessage1 = "The VMware Backup Script couldn't power on the virtual machine '%\^VMIdentifier^%' in a reasonable time.__"
VMStartupErrorMessage2 = "Maybe the machine could not start the VMWare Tools. Please check it's state and/or configuration."
VMStartupErrorMessage3 = ""
VMStartupErrorMessage4 = "Backup processing will continue and you should expect another message."

ArchiveCreationErrorMessageLines = 4
ArchiveCreationErrorMessage1 = "The VMware Backup Script couldn't create %\^ZipFile^%.__"
ArchiveCreationErrorMessage2 = "Please check if you have enough disk space on %\^BackupPath^% and run the backup script again."
ArchiveCreationErrorMessage3 = ""
ArchiveCreationErrorMessage4 = "Note: The uncompressed virtual machine files were NOT deleted from %\^BackupPath^%."

ZipFileSizeErrorMessageLines = 7
ZipFileSizeErrorMessage1 = "The compress operation completed successfully however the zip file is smaller than expected.__"
ZipFileSizeErrorMessage2 = "Please check that all files were compressed and exist in %\^ZipFile^%.__"
ZipFileSizeErrorMessage3 = "Also check that there is enough disk space on %\^BackupPath^%."
ZipFileSizeErrorMessage4 = ""
ZipFileSizeErrorMessage5 = "The zip file is approximately %\^ZipFileSize^% GB."
ZipFileSizeErrorMessage6 = "The zip file was expected to be over %\^MinFileSize^% GB."
ZipFileSizeErrorMessage7 = "Note: The uncompressed virtual machine files were NOT deleted from %\^BackupPath^%."

FreeDiskSpaceCriticalLines = 1
FreeDiskSpaceCritical1 = "*** THERE IS NOT ENOUGH FREE DISK SPACE TO BACKUP AGAIN! ***"

FreeDiskSpaceWarningLines = 1
FreeDiskSpaceWarning1 = "*** There may not be enough free disk space to backup again. ***"

SuccessMessageLines = 14
SuccessMessage1 = "The VMware Backup Script backed up the virtual machine '%\^VMIdentifier^%' successfully."
SuccessMessage2 = ""
SuccessMessage3 = "Backup saved as %\^ZipFile^%."
SuccessMessage4 = "VM was offline %\^TimeVMOff^% minutes between %\^TimeVMShutdownStart^% and %\^TimeVMRestarted^%."
SuccessMessage5 = "The backup operation was paused for %\^TimePaused^% minutes."
SuccessMessage6 = "The compress operation took %\^TimeCompressing^% minutes."
SuccessMessage7 = ""
SuccessMessage8 = "The VM is approximately %\^VMsize^% GB."
SuccessMessage9 = "The zip file is approximately %\^ZipFileSize^% GB."
SuccessMessage10 = "There is approximately %\^BackupDriveFreeSpace^% GB free on the backup location."
SuccessMessage11 = ""
SuccessMessage12 = "Total run time was %\^TimeTotal^% minutes."
SuccessMessage13 = "Start Time: %\^VMShutdownStart^%."
SuccessMessage14 = "End Time: %\^ArchiveCreated^%."

'***********************************************************************************************************************************
'No need to touch anything after this point
'***********************************************************************************************************************************
Const vmExecutionState_On = 1
Const vmExecutionState_Off = 2
Const vmExecutionState_Suspended = 3
Const vmExecutionState_Stuck = 4
Const vmExecutionState_Unknown = 5
Const vmPowerOpMode_Hard = 1
Const vmPowerOpMode_Soft = 2
Const vmPowerOpMode_TrySoft = 3

Const OneMB = 1048576
Const OneGB = 1073741824
Const OneSecond = 1000
Const OneMinute = 60000
Const OneHour = 3600000

'Create objects
Set mailing = CreateObject("CDO.Message")
Set wshNet = CreateObject("WScript.Network")
Set wshShell = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")

'Uncomment to test messages
'Setup_Mail_System ("")
'Error_Encountered Build_Message("VariablesErrorMessage"),true

'Check for errors (decent chance of a typo in all those messages above)
If Err.number 0 then
Setup_Mail_System ("")
Error_Encountered Build_Message("VariablesErrorMessage"),true
end if

'Create VMCOM objects
Set cp = CreateObject("VmCOM.VmConnectParams")
Set server = CreateObject("VmCOM.VmServerCtl")
Set thevm = CreateObject("VmCOM.VmCtl")

'Check for VCOM errors
If Err.number 0 then
Setup_Mail_System ("")
Error_Encountered Build_Message("VCOMErrorMessage"),true
end if


Function Build_Message (byval Message)
'*******************************************************************************************
'Builds a message to be displayed to the user. It Takes a single string parameter "x".
'It looks for variables defined as X + "Lines" and X + <number>.
'X + "lines" is the number of lines for the message and each X + <number> is a message line.
'It loops through all the message lines to build the message. Message lines can contain
'variables which must be preceeded by "%\^" and followed by "^%". The variables will be
'decoded and and their current value will be inserted into the message.
'*******************************************************************************************
On Error Resume Next

'Initialize temp value
TempMessage = ""
'Get number of lines in message
j = eval(cstr(Message) + "Lines")
'Loop through all the message lines
for i = 1 to j
'Get a message line
Junk = eval(cstr(Message) + cstr(i))
'Handle line feeds
if right (Junk, 2) = "__" then
Junk = left (Junk, len (Junk) -2) & " "
else
Junk = Junk & vbcrlf
end if
'Get position of variable in message line
pos1 = instr (1, Junk, "%^")
Pos2 = instr (1, Junk, "^%")
'Process all variables in the message line
while pos1 + pos2 > 0
'Get the variable name
var = mid(Junk, pos1 +2, (pos2 - pos1) - 2)
'replace the varialbe placeholder with the variable name
Junk = replace(Junk, "%\^" & var & "^%", eval(var))
'Check for more variables in the line
pos1 = instr (1, Junk, "%^")
Pos2 = instr (1, Junk, "^%")
wend
'Add the message line to the complete message
TempMessage = TempMessage & Junk
next
'Return the complete message
Build_Message = TempMessage

end function

Sub Delete_Old_Backup_Files (byval VMName, byval BackupFolder)
'*******************************************************************************************
'Deletes older backup files to conserve disk space.
'*******************************************************************************************
On Error Resume Next

set FSO = createobject("scripting.filesystemobject")
set Folder = FSO.getfolder(BackupFolder)
set Files = Folder.Files
Dim NFileArray ()
Dim MFileArray ()

'Initialize values now that we can
RealFileCount = Folder.Files.Count
redim NFileArray (RealFilecount)
redim MFileArray (RealFileCount)

'Fetch the list of files
MyFileCount = 0
for each file in Files
'Only files matching the VM identifier count
if strcomp (left(file.name, (len(VMName)+1)), VMName & "-",1) = 0 then
'Only files bigger than "x" GB in size count
if file.size >= (MinFileSize * OneGB) then
MyFileCount = MyFileCount + 1
NFileArray(MyFileCount) = file
MFileArray(MyFileCount) = File.DateLastModified
end if
end if
next

'No sense doing anything else if less files then max allowed
if MyFileCount > NumberBackupsToKeep then
'Sort by modified date
for i = 1 to MyFileCount
for j = (i + 1) to MyFileCount
if MFileArray(i) < MFileArray(j) then
NBuffer = NFileArray(j)
MBuffer = MFileArray(j)
NFileArray(j) = NFileArray(i)
MFileArray(j) = MFileArray(i)
NFileArray(i) = NBuffer
MFileArray(i) = MBuffer
end if
next
next
'Delete part
for n = NumberBackupsToKeep + 1 to MyFileCount 'Array position zero is blank
Set Deletefile = FSO.getfile(NfileArray(n))
Deletefile.delete true
next
end if

'Destroy objects
set FSO = nothing
set Folder = nothing
set Files = nothing

end sub

Sub Setup_Mail_System (byval VMName)
'*******************************************************************************************
'Setup the mail system. Made into becasue I wanted to send notification if the arguements
'passed to the script were bad.
'*******************************************************************************************
On Error Resume Next

mailing.To = ReportToMail
if VMName is not null then
mailing.from = "VM-" & ucase(VMName) & "@" & MyMailDomain
else
mailing.from = "VM-**Unknown**" & "@" & MyMailDomain
end if
mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = SMTPServer
mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = SMTPPort

end sub

sub Error_Encountered (byval ErrorMessage, byval StopError)
'*******************************************************************************************
' Write a message to the application log, send email (& messagebox if interactive) and quit
'*******************************************************************************************
On Error Resume Next

wshShell.LogEvent 1, ErrorMessage
if StopError then
mailing.Subject = DefaultMailSubject & "Critical Error"
else
mailing.Subject = DefaultMailSubject & "Warning"
end if
mailing.TextBody = ErrorMessage
mailing.Configuration.Fields.Update
mailing.Send
If way="i" Then
Cry = msgBox(ErrorMessage,vbCritical,DefaultMailSubject)
End If
if StopError then
Destroy_Objects
WScript.Quit
end if

end sub

Function ISO_DateTime (byval dt, byval dttype, byval NoSpecialChars)
'*******************************************************************************************
'Converts dates/Times to ISO format
'First parameter is the date/time
'Second is the type of conversion: 1=Date Only, 2=Time only, anything else does both
'Third determines if the ":" can appear in the time
'*******************************************************************************************
On Error Resume Next

dim y: y=year(dt)
dim m: m=month(dt)
dim d: d=day(dt)
dim h: h=hour(dt)
dim n: n=minute(dt)
dim s: s=second(dt)

if m < 10 then m="0" & m
if d < 10 then d="0" & d
if h < 10 then h="0" & h
if n < 10 then n="0" & n
if s < 10 then s="0" & s

'Handle Date
TheDate = y & "-" & m & "-" & d
'Handle Time
if NoSpecialChars then
TheTime = h & n & s
else
TheTime = h & ":" & n & ":" & s
end if
'Combine for Date/Time
TheDateTime = TheDate & "T" & TheTime

'Return whichever value the user wanted
if dttype = 1 then
ISO_DateTime = TheDate
elseif dttype = 2 then
ISO_DateTime = TheTime
else
ISO_DateTime = TheDateTime
end if

end Function

sub Destroy_Objects ()
'*******************************************************************************************
'Destroy the various objects we created. Made into a sub because the script quits from
'more then one place (if errors).
'*******************************************************************************************
On Error Resume Next

'Destroy objects
Set mailing = nothing
Set wshNet = nothing
Set wshShell = nothing
Set fso = nothing
Set thevm = Nothing
Set server = Nothing
Set cp = Nothing
set VMFolderObject = nothing
set BackupDriveObject = nothing
set ZipFileObject = nothing
set args = nothing
WScript.Sleep 2 * OneSecond

end sub


'Check if 7zip is installed
Err.clear
seven_zip_reg = wshShell.RegRead("HKLM\SOFTWARE\7-Zip\Path")
'Check for errors
If Err.number 0 then
Setup_Mail_System ("")
Error_Encountered Build_Message("No7ZipInstalledErrorMessage"),true
end if

'Get the name of the VM delivered by the script argument. Number of arguements must be between 0-2
'If none, then prompt the user for values
'If one, then the user only specified the VM to backup and use default backup file
'If two, then the user wants to define the VM to backup and backup file manually
'If three or more than there is something wrong
Set args = WScript.Arguments
if args.count=0 then 'We are in the interactive mode, way = "i(nteractive)"
'Prompt for the name of the vmfile
vmfile = inputBox("Please enter the full path to the .vmx file of the virtual machine you want to backup:",DefaultMailSubject,DefaultVMPath)
'Quit if cancel
if vmfile = "" then
Destroy_Objects
WScript.Quit
end if
'Determine the VM Identifier based on the vmfile location
VMFolder = fso.GetparentFoldername(vmfile)
set VMFolderObject = fso.Getfolder (VMFolder)
VMIdentifier = VMFolderObject.name
'prompt for the name of the zipfile
TempValue = DefaultBackupPath & VMIdentifier & "-" & ISO_DateTime(now, 0, true) & ".zip"
ZipFile = inputBox("Now, please enter the full path to the .zip file the script will create:",DefaultMailSubject,TempValue)
'Quit if cancel
if ZipFile = "" then
Destroy_Objects
WScript.Quit
end if
'Determine the location where the temporary backup files will be saved
BackupPath = fso.GetParentFolderName(ZipFile) & "\" & VMIdentifier
way = "i"
elseIf args.Count=1 Then 'We are in the mode with predefined vm by parameter, way = "a(utomatic)"
vmfile = args(0)
'Determine the VM Identifier based on the vmfile location
VMFolder = fso.GetparentFoldername(vmfile)
VMFolderParent = fso.GetparentFoldername(vmfolder)
If remote_server = true Then
VMIdentifier = Replace(Replace(vmfolder, VMFolderParent, ""),"\","")
vmfolder = remote_share & "\" & VMIdentifier
set VMFolderObject = fso.Getfolder (remote_share & "\" & VMIdentifier)
else
set VMFolderObject = fso.Getfolder (VMFolder)
VMIdentifier = VMFolderObject.name
End If
ZipFile = DefaultBackupPath & VMIdentifier & "-" & ISO_DateTime(now, 0, true) & ".zip"
'Determine the location where the temporary backup files will be saved
BackupPath = fso.GetParentFolderName(ZipFile) & "\" & VMIdentifier
way = "a"
ElseIf args.Count=2 Then 'We are in the automatic mode with 2 Arguments: VM and backup location
vmfile = args(0)
'Determine the VM Identifier based on the vmfile location
VMFolder = fso.GetparentFoldername(vmfile)
VMFolderParent = fso.GetparentFoldername(vmfolder)
If remote_server = true Then
VMIdentifier = Replace(Replace(vmfolder, VMFolderParent, ""),"\","")
vmfolder = remote_share & "\" & VMIdentifier
set VMFolderObject = fso.Getfolder (remote_share & "\" & VMIdentifier)
else
set VMFolderObject = fso.Getfolder (VMFolder)
VMIdentifier = VMFolderObject.name
End If
ZipFile = args(1)
'Determine the location where the temporary backup files will be saved
BackupPath = fso.GetParentFolderName(ZipFile) & "\" & VMIdentifier
'Create the backuppath folder if it does not exist
If Not fso.FolderExists(BackupPath) Then
newfolder = fso.CreateFolder (BackupPath)
End If
way = "a"
Else 'There are more than two arguments provided: Error
Setup_Mail_System ("")
Error_Encountered Build_Message("InvalidArguementsMessage"), true
End If

Setup_Mail_System (VMIdentifier)

'Before doing anything else check if there is enough disk space to just copy the VM files
VMSize = round(VMFolderObject.size / OneGB, 2)
BackupDrive = fso.GetDriveName(zipfile)
Set BackupDriveObject = fso.GetDrive(BackupDrive)
BackupDriveFreeSpace = round(BackupDriveObject.availablespace / OneGB, 2)
'Don't continue if not enough space
if VMSize >= BackupDriveFreeSpace then
Error_Encountered Build_Message("InsufficientDriveSpaceErrorMessage"),true
end if

'Adding the remote server connection info if necessary
If remote_server = true Then
cp.hostname = remote_host
cp.username = remote_user
cp.password = remote_pass
cp.port = remote_port
End If

'Connect to the server
Err.clear
connected_s = False
For tries_srv = 1 To ServerConnectMaxTries
server.Connect cp 'this method has a built in 2 min timeout
If Err.number = 0 Then
connected_s = True
Exit For
End If
WScript.Sleep ServerConnectTryInterval * OneSecond
Next
'Check for server connection errors
If Not connected_s Then
Error_Encountered Build_Message("NoServerConnectionErrorMessage"), true
End If

'Connect to the virtual machine
Err.clear
connected_m = False
For tries_vm = 1 To VMConnectMaxTries
thevm.Connect cp, vmfile 'this method has a built in 2 min timeout
If Err.number = 0 Then
connected_m = True
Exit For
End If
WScript.Sleep VMConnectTryInterval * OneSecond
Next
'Check for VM connection errors
If Not connected_m Then
Error_Encountered Build_Message("NoVMConnectionErrorMessage"), true
End If

'Used for reporting time of operations
VMShutdownStart = now

'Get the ExecutionState of the vm to know if it must be started after backup complete
ExecutionState = thevm.ExecutionState
if ExecutionState = vmExecutionState_On then
VMWasOn = true 'It must be powered on after backup
elseIf ExecutionState = vmExecutionState_Off then
VMWasOn = false 'After backup do nothing
'We have a VM state error
else
Error_Encountered Build_Message("VMStateErrorMessage"), true
end If

'Get the approximate number of seconds from the start of VMWare Tools inside the vm.
HeartBeat = thevm.Heartbeat
if VMWasOn = true then
'VM without VMWare Tools can only be backed up if it was off.
'If no heartbeat then vmwaretools are not installed or sopmething is wrong.
if HeartBeat < 1 then
Error_Encountered Build_Message("VMWareToolsErrorMessage"), true
end if
end if

'Shut down the VM
VMIsOff = False
For tries_off = 1 To VMStopMaxTries
getoff = thevm.stop(vmPowerOpMode_Soft) 'this method has a built in 4 min timeout
PowerState = thevm.ExecutionState
If PowerState = vmExecutionState_Off Then
VMIsOff = True
Exit For
End If
WScript.Sleep VMStopTryInterval * OneSecond
Next
'Check for VM shutdown errors
If Not VMIsOff Then
'We told the vm to shut down and it did not, we need to check if the VM is hung
for Check_If_Hung = 1 to VMStopMaxHungChecks
'This will tell us how long the vm has been unresponsive
ToolsLastActive = thevm.ToolsLastActive
if ToolsLastActive < VMStopHungSeconds then
WScript.Sleep ( 1 + VMStopHungSeconds - ToolsLastActive) * OneSecond
else
'At this point we can assume the vm is hung and try a hard shutdown
For tries_off = 1 To VMStopMaxTries
getoff = thevm.stop(vmPowerOpMode_Hard) 'this method has a built in 4 min timeout
PowerState = thevm.ExecutionState
If PowerState = vmExecutionState_Off Then
VMIsOff = True
'Not really an error but want the user to know the shutdown was hard.
Error_Encountered Build_Message("VMShutdownHardErrorMessage"), false
Exit For
End If
WScript.Sleep VMStopTryInterval * OneSecond
Next
'Check for VM shutdown errors
If Not VMIsOff Then
Error_Encountered Build_Message("CriticalVMShutdownErrorMessage"), true
end if
end if
next
If Not VMIsOff Then
'The vm didn't shut down but does not appear to be hung
Error_Encountered Build_Message("VMShutdownErrorMessage"), true
end if
end if

'Machine is shut down and can be copied
If remote_server = true Then
vmfolder = remote_share & "\" & VMIdentifier
End If
copyVM = fso.CopyFolder(vmfolder,BackupPath) 'checked
'Machine copied!

'If the VM was originally on then turn it back on now that copying is done
if VMWasOn = true then
VMIsOn = False
For tries_on = 1 To VMStartMaxTries
geton = thevm.start(vmPowerOpMode_Soft) 'this method has a built in 4 min timeout
Heartbeat = thevm.Heartbeat
'Wait until the heartbeat becomes more than 300
If HeartBeat > VMStartedHeartbeat Then
VMIsOn = True
Exit For
End If
WScript.Sleep VMStartTryInterval * OneSecond
Next
If Not VMIsOn Then
'Check for VM Startup errors
Error_Encountered Build_Message("VMStartupErrorMessage"), false
end if
end if

'Used for reporting time of operations
VMRestarted = now

'Pause
PauseStarted = now
WScript.Sleep PauseBeforeCompress * OneMinute
PauseEnded = now

'Create the zip command
ZipCommand = chr(34) & seven_zip_reg & "\7z.exe" & chr(34) & " a -tzip " & chr(34) & ZipFile & chr(34) & " " & chr(34) & BackupPath & "\*" & chr(34) & seven_zip_switch
'Create the archive
CreateArchive = wshshell.Run(ZipCommand,0,true)
'Check for archive creation errors
if CreateArchive > 0 then
Error_Encountered Build_Message("ArchiveCreationErrorMessage"), true
end if

'Check if the zip file is the minumum expected size (no better way to check if the zip operation ran out of disk space but was successfull)
set ZipFileObject = fso.getfile(ZipFile)
ZipFileSize = round(ZipFileObject.size / OneGB, 2)
if ZipFileSize <= MinFileSize then
Error_Encountered Build_Message("ZipFileSizeErrorMessage"), true
end if

'Delete the temporary backup folder
deltmp = fso.deleteFolder(BackupPath)
WScript.Sleep 2 * OneSecond

'if enabled, delete backups not needed any more
if CleanUpBackupFiles then
Delete_Old_Backup_Files VMIdentifier, fso.GetParentFolderName(ZipFile)
end if

'Used for reporting time of operations
ArchiveCreated = now

'Calculate statistics
BackupDriveFreeSpace = round(BackupDriveObject.availablespace / OneGB, 2) 'Need to check again after operation
TimeVMOff = DateDiff("n",VMShutdownStart, VMRestarted)
TimePaused = DateDiff("n",PauseStarted, PauseEnded)
TimeCompressing = DateDiff("n",PauseEnded, ArchiveCreated)
TimeTotal = TimeVMOff + TimeCompressing + TimePaused
TimeArchiveCreated = ISO_DateTime(ArchiveCreated, 2, false)
ArchiveCreated = ISO_DateTime(ArchiveCreated, 0, false)
TimeVMShutdownStart = ISO_DateTime(VMShutdownStart, 2, false)
VMShutdownStart = ISO_DateTime(VMShutdownStart, 0, false)
TimeVMRestarted = ISO_DateTime(VMRestarted, 2, false)
VMRestarted = ISO_DateTime(VMRestarted, 0, false)

'Build the FreeDiskSpace warning message if necessary.
if ((vmsize + zipfilesize) * (FreeDiskSpaceCriticalThreshold / 100)) >= BackupDriveFreeSpace then
DiskSpaceMessage = Build_Message("FreeDiskSpaceCritical")
elseif ((vmsize + zipfilesize) * (FreeDiskSpaceWarningThreshold / 100)) >= BackupDriveFreeSpace then
DiskSpaceMessage = Build_Message("FreeDiskSpaceWarning")
else
DiskSpaceMessage = ""
End If

'Generate and send the success message
Success_Message = Build_Message("SuccessMessage")
if DiskSpaceMessage "" then
Success_Message = DiskSpaceMessage & vbcrlf & vbcrlf & Success_Message & vbcrlf & vbcrlf & DiskSpaceMessage
end if
wshShell.LogEvent 0, Success_Message
mailing.TextBody = Success_Message
mailing.Subject = DefaultMailSubject & "Complete"
mailing.Configuration.Fields.Update
mailing.Send
if way = "i" Then
Cheer = msgBox(Success_Message, vbExclamation, DefaultMailSubject)
end if

Destroy_Objects

WScript.Quit
[/code]


Okay, i figured it out.
In the script only put the IP from the remote server.
Then when running the script (interactive) only put the path that's local on the remote server. c:\virtual machines\vm1\vm.vmx

The script creates the path: \\ip\c$\virtual machines\vm1\vm.vmx

At least this works on the 'Potsdam' script.
Regards,
Patrick

Message was edited by:
petjez

This is the error message i get when my script now runs at night:

-----------------------------------------------------
The VMware Backup Script couldn't create G:\backups\SBSVmware-2007-01-09T000300.zip. Please check if you have enough disk space on G:\backups\SBSVmware and run the backup script again.

Note: The uncompressed virtual machine files were NOT deleted from G:\backups\SBSVmware.
--------------------------------------------------------

But my G:\ drive has 234 GB free and the copy of the vmware is only like 10 GB... so why does it give me this error? What I have in my script is to check to see if there is already 5 backups and if there are to delete the olest one but it doesnt seem to do that... can that be the problem? two nights in a row i got the same above message with more than enough free space on my server!!!!! ahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

i can post my code again if u want.... here is the part of delete the old backups:

----------------------------------------------------
check is archive is valid)
NumberBackupsToKeep = 5 'Maximum number of backups per VM to keep. Oldest backups above this number are deleted
MinFileSize = 2 'Minimum file size (gb) for an existing backup file to be considered valid
-------------------------------------------------

Please HELP!!!!!!!!!!!!!


One thing to consider is that old backups are only deleted AFTER the a successfull backup is created. This means it's done after the files are zipped. The script bails out before the zip operation so the deletion of old backups never occurs. This is not the problem.

The good news is that you can manually finish the backup by zipping the files yourself (this is why the uncompressed files are left on the drive).

You are receiving the "ArchiveCreationErrorMessage" which you can customize that message to suit your needs. This message is triggered when the zip operation fails. The only reason I could think of why the zip operation would fail is due to insufficent disk space. This is why I defined the text for that message the way I did. Disk space is not necessarilly the reason for the failure though.

The real issue is that the zip file could not be created, for whatever reason. We need to determine that reason.

Is the script you posted a couple of days ago what you are still using?

what i ahve done is taken your above newley posted script and applied my settings to it and put it on my server. My backup runs at 12:02 AM so in the morning I will be able to see if my backup completed or not. Will let you know thet status tmrw!

thx 4 ur help so far!

Try this too. Just replace the existing block with this new one. It's just a new error message that should be a little bit more helpful.

Also one more thing to check. Go to your 7-zip install folder. Do you have a file called 7z.exe?

code
ArchiveCreationErrorMessageLines = 5
ArchiveCreationErrorMessage1 = "The zip command, ^%ZipcCommand%^, failed with code ^%CreateArchive%^.__"
ArchiveCreationErrorMessage2 = "The VMware Backup Script couldn't create %\^ZipFile^%.__"
ArchiveCreationErrorMessage3 = "Please check if you have enough disk space on %\^BackupPath^% and run the backup script again."
ArchiveCreationErrorMessage4 = ""
ArchiveCreationErrorMessage5 = "Note: The uncompressed virtual machine files were NOT deleted from %\^BackupPath^%."
[/code]

Where's the latest copy of this whole script?

I copied what I thought was the latest, but it didn't seem to work.

The original post ran, but I know it doesn't have the latest code.

I'm wondering if someone could host it...

The absolute latest isn't posed in it's entirety. The closest is 7 posts up. The only difference between the latest and greatest and this version is the minor change 2 posts up.

Message was edited by:
SirShagg

Tried that one...

Doesn't even execute for me.

Happened across another slight issue. This one concerns the email notification. The FROM addres of the email is constructed using the virtual machine identifier. However the identifier might contain characters which can't be used in an email address. This will not affect the backup but will prevent you for getting any notifications about the backup.

To fix the problem I added a new function and updated the code to call this new function. If you want to implement this then:

Paste this
code
Function COC (byval Temp)
'*******************************************************************************************
'Convert all characters other than a-z, A-Z, 0-9, underscore, and hyphen to underscore
'*******************************************************************************************
On Error Resume Next

Dim i
Dim J
Dim v

i = 1
j = Mid(Temp, i, 1)
While J ""
v = asc(j)
If (v >= 48 and v <= 57) or (v >= 65 and v <= 90) or (v >= 97 and v <= 122) or v=45 or v=95 then
else
Temp = Mid(Temp, 1, (i - 1)) & "_" & Mid(Temp, (i + 1), Len(Temp))
i = i - 1
End If
i = i + 1
j = Mid(Temp, i, 1)
Wend
COC = Temp

End function
[/code]
just before
code
'Check if 7zip is installed
Err.clear
seven_zip_reg = wshShell.RegRead("HKLM\SOFTWARE\7-Zip\Path")
[/code]

AND

Change this line
code
Setup_Mail_System (VMIdentifier)
[/code]
to
code
Setup_Mail_System (COC(VMIdentifier))
[/code]


Well, we are just about to test putting our VM server into production and I am looking at the backup situation. I ran into this advanced script, so I thought I would check it out.

Unfortunately, it doesn't seem to be running for me at all. I have 7zip installed. When I run the script, it just returns to the prompt with no output at all, no error, no prompt, etc. I am not sure why nothing is running. . .I will have to test that more I guess.

The other question I had is in regards to timing of the backups:

Has anyone tested the time difference between the copying then compressing then copying the compessed file vs just plain copying the files directly to a network location? The reason I wonder if that if the timing is about the same, it might be nicer/better to put the files on the remote system directly since they would also be ready to be used on that remote system if needed. With the compression issue, you would have to uncompress the files before you could boot them in case of recovery (seems like it would probably take hours on a sizeable disk file). Anyway, just looking for input. . .because then I would approach the compression on the remote system later for archiving multiple versions of the backup and leave one copy uncompressed ready to start. . .??

Of course if the resulting time is still much shorter with the copy,compress,copy method, then this is the way to go.

That does seem odd. At the least it should be emailing you with what the error was. I'd suggest to check your mail settings
code
'Define your mail settings
[/code]
Make sure your mail server will accept messages from the machine running the backup script and does not discard them as spam.

You can also setup a message box on an error. Find this subroutine:
code
sub Error_Encountered (byval ErrorMessage, byval StopError)
[/code]
and replace
code
if StopError then
Destroy_Objects
WScript.Quit
end if
[/code]
with
code
if StopError then
Destroy_Objects
msgbox ErrorMessage
WScript.Quit
end if
[/code]

This way the script will display the error message on the screen and you will know two things. 1) What the error is 2) You DO have a problem with your mail settings. Now if it does not display an error....hmmmm

It would probably be good to post the command line you are using.

I will try defining those settings. Part of the complication is that our mail server usually only accepts over SSL from trusted sources and I don't see that ability in the script. I will reconfigure the mail server to allow this testing. Is there any other log or error output I can check? I will be adding in the message code you mentioned.

Pretty much all output is done via email. That modification I posted will output the message to seceen as well as email. Note: you would not want to do this permanently since the script waits for you to click the OK button on the screen message before it continues.

TechFan,

The following is a modified version of just the mailing code from the script. Could you save it as test.vbs and give it a try to see if it will work for your mail server with SSL. If so I could incorporate the changes into the script.

code
'Define your mail settings
ReportToMail = "me@mydomain.com" 'Here you'll receive mail messages.
MyMailDomain = "mydomain.com" 'Your mail domain name
SMTPServer = "mail.mydomain.com" 'IP address or host name. Server must be able to relay mails for your address
SMTPPort = 25 '25 is standard
SMTPAuth = cdoAnonymous 'cdoAnonymous, cdoBasic, or cdoNTLM. Leave the default if you do not know
SMTPUser = "" 'Authenticate as this user. Leave the default if you do not know
SMTPPassword = "" 'Authenticate using this password. Leave the default if you do not know
SMTPSSL = false 'Use SSL? Leave the default if you do not know
SMTPTimeout = 60 'Default timeout. Leave the default if you do not know
DefaultMailSubject = "" 'Subject line for email message, end with ": " if used. (the script code adds to this)
ScreenMessageOnStopError = false 'Set true to display stop errors to screen (in case email is not working)

'***********************************************************************************************************************************
'No need to touch anything after this point
'***********************************************************************************************************************************

Const cdoAnonymous = 0
Const cdoBasic = 1
Const cdoNTLM = 2

VMName = "crap"

Set mailing = CreateObject("CDO.Message")

mailing.To = ReportToMail

if not isnull (VMName) then
mailing.from = "VM-" & ucase(VMName) & "@" & MyMailDomain
else
mailing.from = "VM-**Unknown**" & "@" & MyMailDomain
end if
mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = SMTPServer
mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = SMTPPort
mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = SMTPAuth
mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername") = SMTPUser
mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword") = SMTPPassword
mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = SMTPSSL
mailing.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = SMTPTimeout
mailing.Configuration.Fields.Update

Mailing.TextBody = "This is some sample message text.."

Mailing.Send
[/code]


The modified email script works.

I am calling the script:

vm-backup "C:\VM\SERVER1\Windows 2000 Server.vmx"

In interactive mode it asks me for server name and backup location, but then nothing happens. The power went out, so the VM is actually powered off during today's testing. . .does the backup fail if the machine is already off?

Ok, I think I found it. Remote server was set to True even though I was trying to run it from the local machine. I did that and it shutdown the machine (not suspend for some reason) and started copying the files. So, that crazy default of remote server was the main prob. . .

Unfortunately, partly through the copy, I got the same error "Error was can't make appropriate connection to the server. . .etc." Then the entire host restarted. . .ugh.

Good to hear that the modified email works.
If the VM is off it will backup but the VM will not be turned on afterwards.
The VM is shutdown, not suspended for the backup. It's done this way because if backed up when suspended you may have problems restoring it on different hardware.
That remote server setting would have done it. I meant to change that to false last time I posted the script , but yep you need to go through the variables section to make sure they are right for you.

The HOST restarted? I would expect the GUEST to restart. Did some of the files actually get copied?

Guys this looks awesome, is there a consolidated version of the script that can be used. There seems to have been different people adding different things etc and i am not sure which to use

Craig

I asked for this the other day... Still waiting...

There are two scripts here. The first one is by Saxa. The second is one by me and is at the core it's still Saxa's original script. I was not able to easily read this original script and decided to reformat it so that I could read and understand it. That's when my endless cycle of tweaking it started. It's pretty much done now but every once in a while I find some mistake, a better way to do something, or think of something new to add. Sometimes people make suggestions in the forum and I try to implement them. There have also been many suggestions, or code snippets, from people that have not been implemented in either script.

By all means feel free to use whatever parts of the script you like and make changes to the parts you don't. In the end the script has to work for you. If you feel like sharing any of your changes, please do.

As for me, I'm looking to find a place to permanently host my version of the the full script. I'll keep that up to date as changes are made. I know it's difficult to follow all the "change" instructions and posting the whole thing here each time is a bit much. Once I find a place to host it I'll post a link.

In the meantime the best one to use is at the top of page 7. Note: you probably need to change the remote server value to false.

The one on the top of Page 7 works a treat, and the remote works brilliantly once you get your head around it and how it should work.

Now to get a gruntier machine at work to do multiples at a time, otherwise running 4-5 7z sessions tends to kill my box. ;)

Good work done by all, hopefully this will save my bacon a bit with VM machines not only here but at our other sites!

Well, I installed SP1 on win2003. . .had just set up a quick win2003 test box. . .and now the host doesn't restart when copying large files. Doing first live backup now. Copy still seems slow.

Ok, it took 1 hour to copy 28GB of files (this is on WD 500GB SATA drive). Now doing the 7zipping.

I was not able to easily read this original script and decided to reformat it so that I could read and understand it.

Obviously my English wasn't good enough :)

it took 1 hour to copy 28GB of files (this is on WD 500GB SATA drive)

I'm also using WD's SATA drives here; 1 hour to copy 28GB is too long, IMHO.

Check your storage subsystem. Or are you copying from the HDD to itself? Maybe antivirus is checking your files? You should make an exclusion for .vmdk files.

On my server it never takes more than 25 minutes to copy 52 GB (2 files; 16 + 36) from one HDD to another...

It wasn't that at all.

I need loops to be indented and such (parenthesis where they aren't really needed, etc). All the blank lines also threw me off. No fault of yours. I'm just not a great programmer so when I looked at it I was not able to follow what was going on. :)

Also depends on network speed if you are copying to another machine.

Additionally multiple simultaneous copy operations can slow down all copy operations.

Also zipping one VM while still copying another can also slow down the copy.

I use gigabit switches and can copy 2 36gb VM's in roughly 30 minutes. Adding a third slows them all down just a bit. I set the script to wait for all copy operations to end before zipping so as to minimize the VM downtime.

Now to get a gruntier machine at work to do multiples
at a time, otherwise running 4-5 7z sessions tends to
kill my box. ;)

:)

:)

Also depends on network speed if you are copying to
another machine.

OK, I "was local", i.e. not on the network, but inside one machine...

Additionally multiple simultaneous copy operations
can slow down all copy operations.

Right!

I use gigabit switches and can copy 2 36gb VM's in
roughly 30 minutes. Adding a third slows them all
down just a bit.

Comparable with my results on the network. Usin' gigabit switches, too...

Hm, strange. I was copying from the disk to itself. I am running it again now with a second drive added. Then I will try copying to a RAID 0 (2 drives). Then I will try copying to RAID 0 on the same RAID as the system. . .and over the network as well. It just seems very slow for a fast system. Compressing the 28GB took 2 hours. . .don't want to do that too often.

Compressing the 28GB took 2 hours. . .

It's really OK. While compressing, you don't need a fast I/O, but processing power.

My old server needs ~ 4 hours to compress 52 GB. But it's also OK, if you keep in mind that your VM is already running while 7zip works...

I still need to test transferring over Gigabit, but to different drive took 35 minutes for 28GB. I guess I will need to set up another system to do the compression and storage. . .

A suggestion though. . .make it an option to either shutdown or suspend a VM. I am not sure why you would have trouble restoring to another machine. . .you should just be able to delete teh suspended data files and start it up fresh I would think??

A suggestion though. . .make it an option to either shutdown or suspend a VM. I am not sure why you would have trouble restoring to another machine. . .you should just be able to delete teh suspended data files and start it up fresh I would think??

So, the idea and the target of my initial script wasn't to backup a developing VM, but to backup real live production virtualized servers.

If you should ever use some live servers, never take a snapshots of them and never suspend them: you'll get real trouble. Only correct shut down / reboot are your friends.

That's why this option wasn't implemented.

But maybe SirShagg will do it? ;)

Why not suspend? That is what I was hoping to understand.

Why not suspend? That is what I was hoping to understand.

Every service you are running (domain database, SQL etc.), doesn't know, what suspending is. You can't imagine something similar to it on a real box, right?

So, the server apps are writing their transaction logs and data files, and suddenly they don't get their power any more... Until now, it's still OK: server apps are capable to rollback the transactions which wasn't committed yet.

But in order to do that, the full start circle of respective service is required. Which isn't possible while you are resuming the VM which was previously suspended. Your service doesn't know what to do, it thinks "Hey, I had a crash, but my transaction is committed. No way!" and produces a rollback. And it means, your transaction is deleted.

I hope it was well described? :)

Over the above: shutdown or suspend = downtime. Is there a difference if the downtime 5 or 10 minutes?

Message was edited by:
saxa

Yeah, it is not the amount of downtime that is really importantant. . .it is the fact that anything that has to run on the console or that is part of some troubleshooting willl be lost every time you run a scheduled backup. . .

We have at least one dumb piece of software that requires that we are logged into the console for the database to be available. . .and that is one of our planned machines to migrate. . .

We have at least one dumb piece of software that requires that we are logged into the console for the database to be available.

If this part runs on Windows, install TweakUI inside the VM and use it's option to auto-login... It works even on WinNT.

Then, after every reboot, the user is logged in automagically.

Bah, I've been wracking my brains trying to hack together my own solution and can't even get started. I don't want to start making copy of the vmx's as HD space is an issue on production servers. What I want to do is this:

Enumerate a list of the virtual servers on the physical server, find out if they were on or not and write out the path of the servers that were on to a text file, shut down those servers.

Then have a second script that simply resumes the servers from that text file generated from the first script and deletes the text file.. Shouldn't be that hard right?

write out the path of the servers that were on to a text file

Please, could you explain this?

Something like this, but formated into vbscript.

@output = systemcall("vmware-cmd -l")

foreach $line in @output
{
$state = systemcall("vmware-cmd $line getstate")
if($state contains "on")
{
writeToTextFile($line)
systemcall("vmware-cmd $line suspend")
}
}

#Wait while backups are being done then call this script

array txtfile = openfile("textfileofsuspenedVMs.txt")

foreach $line in @txtfile
{
systemcall("vmware-cmd $line start")
}

need any more clarification?


I have this right now,, obviusly I'm a nub, and this doesn't work :(

Const ForReading = 1

Set objShell = CreateObject("Wscript.Shell")
objShell.CurrentDirectory = "C:\program files\vmware\vmware server\"
objShell.Run("%comspec% /k vmware-cmd -l > c:\scripts\vmwarelist.txt")

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile _
("c:\scripts\vmwarelist.txt", ForReading)

strText = objTextFile.ReadAll
objTextFile.Close

arrComputers = Split(strText, vbCrLf)

For Each strComputer in arrComputers
objShell.Run("%comspec% /k" & """ & C:\program files\vmware\vmware server\vmware-cmd & """ & """ & strcomputer & """ & "getstate")

Next


I try to use this script for our environment. I got the first error with 7-zip, event i have the 7za.exe in the 7-Zip folder. I have change the path to point to 7-zip folder. I change the code to directly point to the 7-Zip folder. It's keep telling me that 7-Zip doesn't install in our system.
I try to call it from C:\7za.exe, it doesn't work.
I'm using Window 2003 Server R2, please help

I'm using Window 2003 Server R2

64bit?

I try to use this script for our environment. I got
the first error with 7-zip, event i have the 7za.exe
in the 7-Zip folder. I have change the path to point
to 7-zip folder. I change the code to directly point
to the 7-Zip folder. It's keep telling me that 7-Zip
doesn't install in our system.
I try to call it from C:\7za.exe, it doesn't work.
I'm using Window 2003 Server R2, please help

Which version of the script are you running? Depending on what version it's possible that the error is unrelated to 7zip. If you post the actual error message we can probably tell.

Guys this looks awesome, is there a consolidated
version of the script that can be used. There seems
to have been different people adding different things
etc and i am not sure which to use

Here is the location of the latest version. I will be updatig the file at this location whenever I update the script. I'm also trying to keep a list of changes with it - we'll see how that goes.

http://www.fileden.com/files/2007/1/16/650957/VMBackup.zip


A suggestion though. . .make it an option to either
shutdown or suspend a VM.

But maybe SirShagg will do it? ;)


Sorry, This isn't something I have any plans on doing either for the same basic reasons Saxa pointed out.

Get the latest version of the script here:
http://www.fileden.com/files/2007/1/16/650957/VMBackup.zip

That is too bad. I'll just adjust the code myself if I decided to do it that way instead. First, I will experiement with moving one such suspended machine to another server. . .because we can't have all our servers shutdown every time if there is another option.

Check your storage subsystem. Or are you copying from
the HDD to itself? Maybe antivirus is checking your
files? You should make an exclusion for .vmdk files.

On my server it never takes more than 25 minutes to
copy 52 GB (2 files; 16 + 36) from one HDD to
another...


I still am not getting times anywhere close to yours. . .I have gotten as low as 25 minutes for 28GB. . .??

What could be the bottleneck?

I use gigabit switches and can copy 2 36gb VM's in
roughly 30 minutes. Adding a third slows them all
down just a bit. I set the script to wait for all
copy operations to end before zipping so as to
minimize the VM downtime.

Copying over out gigabit seems to be the fastest. . .it took 19min to copy the same 28GB?? Nothing else being copied during any of the tests. . .

Btw, I just thought of something that could be nice to have. . .would it be possible to have all the settings in a separate file? So that when we use an updated version we don't have to reconfigure? :-)

Can anyone help me out with my script, I don't think what I'm trying to do is too difficult.

I fix the bug with 7-zip by move the 7za.exe to the system32 folder.
However, when i run the script there is nothing happen. My Virtual machine still on and there is no backup file created.
I'm using window 2003 R2 32bit as a host, and window XP as a guest for testing purpose. And i'm using VMWare WorkStation 6.0 Beta

And i'm using VMWare WorkStation 6.0 Beta

You should have said it at first.

The script runs on VMware Server only. Workstation doesn't have required APIs for the script to run. So, you have to back up your VMs manually :)

Ok, i see now. I will test my server first and move it to VMWare server when we are done. Thank you very much saxa.
In addition, do we have to shut down the server for backup or we can suppend it and backup. If you can make it to suppend or tell me how to make it, it's will be more than wonderful. I use my DNS server on one of our guest. If i shutdown the DNS server for long time, it will affect our network.
Thank you for your help

The suspending will be never implemented.

I would suggest you to forget about it right now.

If you want to know why the suspending and/or snapshotting of production servers is dangerous, please read my other posts in this thread.

Here a cite of myself :)

Every service you are running (domain database, SQL etc.), doesn't know, what suspending is. You can't imagine something similar to it on a real box, right?

So, the server apps are writing their transaction logs and data files, and suddenly they don't get their power any more... Until now, it's still OK: server apps are capable to rollback the transactions which wasn't committed yet.

But in order to do that, the full start circle of respective service is required. Which isn't possible while you are resuming the VM which was previously suspended. Your service doesn't know what to do, it thinks "Hey, I had a crash, but my transaction is committed. No way!" and produces a rollback. And it means, your transaction is deleted.

I hope it was well described? :)

Over the above: shutdown or suspend = downtime. Is there a difference if the downtime 5 or 10 minutes?

Message was edited by:
saxa

I see your point.
Thank you for fast respond saxa.

Message was edited by:
naughtyboy119

Btw, I just thought of something that could be nice
to have. . .would it be possible to have all the
settings in a separate file? So that when we use an
updated version we don't have to reconfigure? :-)

Yep, I thought of that one too. If I ever get the time I'll probably give it a go.


Also in regards to suspending:

(second post):
http://www.vmware.com/community/thread.jspa?messageID=407181&#407181

Also see the second post by KevinG here:
http://www.vmware.com/community/thread.jspa?messageID=434750&#434750


All that being said if you still want to implement this then you will need to get yourself a copy of the API docuemntation here: http://www.vmware.com/support/developer/scripting-API/
With the information in that document one should be able to modify the script to backup using suspend.

Message was edited by:
SirShagg


Version 3 is released :) (Link is at the bottom of this post)

Since this one requires changing your startup commands I've also included Version 2 in the distribution. You can choose which to use.

Below are the release notes:
code
1/29/07 - V3.01
This is a rather significant change since the script was modified to run with
only one arguement now. It will be necessary to adjust any scheduled tasks or
shortcuts when using this new version. It is also still possible to run the
script in interactive mode with no arguements.

Starting with this version you should not longer make changes to the default
values in the script. Instead you should use the INI file to override the default
valuse from the script. To do this you will create a new section in the INI file.
In that section you will define all the values which you do not want to use the
defaults. Then when you run the script you pass the section name to the script.

A default INI file is distributed in Zip format so that it will not overwrite your
current INI file. Please be sure to unzip this file as it has additional
information on how to format the INI file.

* Added INI file to hold custom settings
* The INI file can hold many differnt sets of settings and you can choose
which set to use based on the arguement used.
* Now whenever the script is updated you will not need to re-enter your settings
* You now only need one script even if you need to backup multiple machines all
with different settings.
* Some of the very early error messages are now forced to display on screen
instead of in email because the mail settings are not known yet.
* Fixed an issue where errors displayed to screen would not have the correct
message title
* Interactive mode will now calculate the vmidentifier and use it when suggesting a
zipfilename.
* Disabled setting up mail system in interactive mode. By default this would error
out anyway and it caused a significant delay when it did.
* Fixed various typo's in comments
[/code]

Get the latest version of the script here:
http://www.fileden.com/files/2007/1/16/650957/VMBackup.zip

this script is really nice, i have started using it just some days ago because i needed some backup-solution for VMs being hosted on Windows. i typically use linux, but i`m stuck with some windows boxes, too.

really cool solution, thanks for making it!

i`d recommend adding some option to use it without compression - think of using this script for mirroring VMs from server A to server B and hold n copies on server B from the last backup-runs . i have started to workaround this by doing some ugly hacking into the existing script with my very limited knowledge of vb scripting.
for now, i`m unhappy with this, because with the next update of the script i would need to hack this again :D

furthermore, some type of better logging into a logfile would also be useful - maybe different loglevels "info", "warning" and "debug" ?
for example, if you don`t get a mail, you don`t even know if your script was running successfully or if there was a problem with the mailserver. actually, i had the problem that mails didn`t get through because i used 3 recipients (usera@localdomain;userb@localdomain;userc@other-domain) and the mailserver rejected those mail completely - just because of the mailserver not relaying mail to 3rd recipient "userc@other-domain". ok, didn`t check the latest version yet, maybe this already has being adressed - but i first need to hack this to remove compression before i can try ;) :D :D

oh - and i forgot to tell: what about putting those message-definition to separate sort-of "internationalization" files ? so it would be easy to translate those to different languages. i`d be happy to do the german translation and offer doing it !

regards
roland


i`d recommend adding some option to use it without
compression - think of using this script for
mirroring VMs from server A to server B and hold n
copies on server B from the last backup-runs . i have
started to workaround this by doing some ugly hacking
into the existing script with my very limited
knowledge of vb scripting.
for now, i`m unhappy with this, because with the next
update of the script i would need to hack this again
:D

This should be easy enough. I could give it a go the next time I do some editing.

furthermore, some type of better logging into a
logfile would also be useful - maybe different
loglevels "info", "warning" and "debug" ?
for example, if you don`t get a mail, you don`t even
know if your script was running successfully or if
there was a problem with the mailserver. actually, i
had the problem that mails didn`t get through because
i used 3 recipients
(usera@localdomain;userb@localdomain;userc@other-domai
n) and the mailserver rejected those mail completely
  • just because of the mailserver not relaying mail
to 3rd recipient "userc@other-domain". ok, didn`t
check the latest version yet, maybe this already has
being adressed - but i first need to hack this to
remove compression before i can try ;) :D :D

There is a value that will force errors to the scren (in case of email issues): ScreenMessageOnStopError - set thsi value to true. It's no perfect but it should do. I've been trying not to do logging to a file, but it's a possiblity for the future.

oh - and i forgot to tell: what about putting those
message-definition to separate sort-of
"internationalization" files ? so it would be easy to
translate those to different languages. i`d be happy
to do the german translation and offer doing it !

With the way these messages are currently implemented I simply don't know how to read them in from the INI file.

regards
roland

i`d recommend adding some option to use it without
compression - think of using this script for
mirroring VMs from server A to server B and hold n
copies on server B from the last backup-runs . i
have
started to workaround this by doing some ugly
hacking
into the existing script with my very limited
knowledge of vb scripting.
for now, i`m unhappy with this, because with the
next
update of the script i would need to hack this
again
:D

This should be easy enough. I could give it a go the
next time I do some editing.


I have spent a couple of days doing exatly that as it was something I wanted for my solution. I'm refining/testing at the moment, will post the script with changes in next 24 hours or so... Am new at this 'contributing' thing, but SirShagg, you may like to review and include in your distribution? I have kept things consistent to the original and spent some time making sure all permutations still work (keep/delete copy files, do or don't create zip etc) also fixed the problem that you couldn't have the copy files in a different location to the final zip.

Regards,
Chris

Oh, PS. Saxa and SirShagg, thanks for the great script!

Message was edited by:
PCost_CL

Oh, PS. Saxa and SirShagg, thanks for the great script!

yes - indeed!

Chris, can you make your modified script available? i`d like to give it a try and would be happy to give some feedback or report about bugs.

roland

btw - what about adding support for lzop compression? (binary for windows available at http://www.lzop.org/)

lzop is so much faster than 7zip, compression is not as good, but if we need to backup lots of VMs which are big in size, speed is probably more important than saving space.

there is only one caveat: lzop is a compressor more like gzip and not a real archiver, so compressing several files into one is somewhat limited.

roland

Have been trying to sort a bug with the cleanupfiles routine... forgot (as you do) that the number 2 is not the same as the string '2'. Anyway, now I have spotted that problem, the rest should be done v shortly.

My main concern is that it doesn't break any existing setup, while adding the new requirements.

Cheers,
Chris.

With the way these messages are currently implemented I simply don't
know how to read them in from the INI file.

what about this ones ?

http://www.vandyke.com/support/crt/scripts/call_module_vbs.txt
http://www.source-code.biz/snippets/vbscript/5.htm

Hello Roland,

greets from Hessen ;)

btw - what about adding support for lzop compression?

I have never heard about it, it sounds very interesting, especially the quickness...

May I ask you something? I know you are a Linux expert :)

I created a small bash script which does almost the same what this VB-script does (search for it here on the board). For the compression it uses tar in conjunction with gzip (tar cfvz).

It was very impressive for me (I'm a total Linux noob), how quick the compression was...

So, my question: are there tar and gzip for Windows available? If yes, are they so quick, too?

greets from Hessen ;)
thanks.
greets from cologne!
(after some night with too few hours of sleep since you know what`s going on there on thursday before carnival monday ;)
you probably live nearby where the mad scientist (=continuum) lives ? ;)

May I ask you something?
sure - always !

I know you are a Linux expert :)
thanks, but am i? uhhhh - i think there are so many people knowing so much more.....
otoh, i have heard some colleague calling me the "one-eyed among the blind" last week :D

I created a small bash script which does almost the same what this
VB-script does (search for it here on the board).
oh, i must have missed that - thanks for pointing to. i already spend some toughts of doing a port of your vbs script and wondered, why there wasn`t a linux version yet.

For the compression it uses tar in conjunction with gzip (tar cfvz).
sure - what else.....? ;)

It was very impressive for me (I'm a total Linux noob), how quick
the compression was...
gzip should be quicker than zip in general. but - anyway - you will be impressed much more, how quick lzop does compress.
you can also use tar with lzop: "tar --use-compress-program=lzop ....."

So, my question: are there tar and gzip for Windows available?
yes, there are some different ports for windows. most noticeable gnuwin32 collection. most of the ports i have seen have some major caveat: they are note large-file aware, so they cannot handle files >2gb. i`m just testing latest gnuwin32 ports.gzip looks good, tar seems having issues with "-z"

If yes, are they so quick, too?
i don`t have any real-world comparison between linux/windows tar/gzip - i think it depends. i would guess that the cygwin variants shouldn´t perform that well, but i guess the native ports (like gnuwin32) should have similar performance. but i can be wrong.....

regards
roland

Updated script now available at http://www.ourplace.org.nz/vmscript/VM-Backup.zip

This is just the vbs file, you need to original package for the ini and readme stuff (from SirShagg's earlier post).

See notes at head of script for details of changes I have made. Basically, if you want to replace the existing script with this, you need to add one line to your ini file:

DefaultCopyPath=[same as DefaultBackupPath]

this can be any valid path, this new path allows different copy and zip locations, in case you want to copy to one place (local perhaps) and zip to another (removable backup say).

You can also use:
KeepCopyFiles=TRUE (to keep the copy and not delete it)
MakeZippedFile=FALSE (to skip the zip file, ie use with above to just copy the vm files)

The 7Zip check is suppressed, so if you don't have any need to create the zipped file you don't need to install it. Just set the MakeZippedFile=FALSE line.

If anyone has any questions, comments, please let me know.
I'm happy for this to be incorporated into the 'official' version (the comments are just so you can see what I changed, no need to retain them otherwise).

Enjoy.
Chris.

is DefaultCopyPath just a change in terminolory from DefaultbackupPath or is there more significance? (I have not had a change to digest it all yet).

is DefaultCopyPath just a change in terminolory from
DefaultbackupPath or is there more significance? (I
have not had a change to digest it all yet).

No, DefaultBackupPath now refers only to the location to create the zip file.
DefaultCopyPath is additional to this, and specifies the location to copy the vm files to, (uncompressed copy during vm shutdown), and from which the zip will be created.


It looks like a nice addition.

Good catch on the INI substring issue.

With the way these messages are currently
implemented I simply don't
know how to read them in from the INI file.

what about this ones ?

http://www.vandyke.com/support/crt/scripts/call_module
_vbs.txt
http://www.source-code.biz/snippets/vbscript/5.htm


I'm not really sure how to explain it. Essentially I need to have one variable define the name for another variable and I can't seem to do that (not even sure if it's possible). This is just a limitation of the way I implemented the messages.

I think I figued out an easy enough way to change the message processing that I can get this done though. I'll give it a shot this weekend.

I've got the messages moved out to an INI file and working now and am nearly done testing that code. I'm now working on creating a log file during the operation. This might take a few days to worked out, tested and debugged but I'll post it once done.

This version will also retain the additions made by PCost_CL.

I have implemneted your version 3 script and have added stuff to the ini and it seems to almost work 100%
I get an email at the end of the job saying "subject"Critical Error

and this is what the email contains:

The compress operation completed successfully however the zip file is smaller than expected. Please check that all files were compressed and exist in d:\backups\Windows Server 2003 Standard Edition-2007-02-20T133258.zip. Also check that there is enough disk space on d:\backups\Windows Server 2003 Standard Edition.

The zip file is approximately 3.25 GB.
The zip file was expected to be over 1 GB.
Note: The uncompressed virtual machine files were NOT deleted from d:\backups\Windows Server 2003 Standard Edition.


what i dont understand is that in my ini file it says the zip has to be over 1 GB and in this case its is since its 3.25 GB but it still gives me that error message thinking it isnt.... Also I have more than 200 GB free on the backup location so why does it also give me the error to check disk space?

if these 2 issues can be resolved and also for it to delete the backuped up folder that would be great...

can someone pls help me understand what am i doing wrong?
Also does the e-mail no longer tell you how long the vm was down for and how long hte zip operation took? or since i had these errors it doesnt give me that info?

below i have copied and pasted my INI file settings: (everything in the vbs is kept as defualt [version3])

[SERVER2]
DefaultBackupPath=d:\backups\
VMFile=C:\Virtual Machines\Windows Server 2003 Standard Edition\Windows Server 2003 Standard Edition.vmx
CleanUpBackupFiles=TRUE
NumberBackupsToKeep=5
MinFileSize=1
ReportToMail=XX@XXX.com
MyMailDomain=XXX.com
SMTPServer=XXX.com
SMTPPort=25
DefaultMailSubject=blah blah blah

thanks in advance for your help!


Louch,

I think this is the same problem I picked up setting the number of backups to keep, I found that vbscript wasn't finding 10 to be greater than 2.

As far as I can tell, when vars are read in from the ini file, they are defined as strings (if only by default) and that causes things to fall over in comparisons.

Try changing

MinFileSize = GetINIValue(Section, "MinFileSize", MinFileSize, INIContents)

to read

MinFileSize = CInt(GetINIValue(Section, "MinFileSize", MinFileSize, INIContents))

which I think should fix it. I have added this (cast as integer) to various of ini file lines in my reworked version, I understand this will be incorporated in a new release from SirShagg. Otherwise, try the version I posted earlier, note the addition of DefaultCopyPath to make things work with your (otherwise unchanged) ini file.

Chris.

Louch,

I think this is the same problem I picked up setting
the number of backups to keep, I found that vbscript
wasn't finding 10 to be greater than 2.

As far as I can tell, when vars are read in from the
ini file, they are defined as strings (if only by
default) and that causes things to fall over in
comparisons.

Try changing

MinFileSize = GetINIValue(Section, "MinFileSize",
MinFileSize, INIContents)

to read

MinFileSize = CInt(GetINIValue(Section,
"MinFileSize", MinFileSize, INIContents))

which I think should fix it. I have added this (cast
as integer) to various of ini file lines in my
reworked version, I understand this will be
incorporated in a new release from SirShagg.
Otherwise, try the version I posted earlier, note the
addition of DefaultCopyPath to make things work with
your (otherwise unchanged) ini file.

Chris.


I'll second this. The next version already includes your cint additions.

As for the message to check disk space: This is nothing more than the wording I chose for the message. I couldn't think of another reason why the zip command would complete but that the zip file would not be 100%.

The files are purposely not deleted as a precaution since the script thinks the zip failed. This way you still have the backup, just not zipped. This will be resolved when the file size check is fixed.

All the stats, such as time vm was down, zip operations, etc, etc are only in the success message which you are not getting, once again because the file size check fails.

SirShagg,

You can download it from here:
http://www.vmware.com/download/sdk/api.html

it's not a correct API version; it's the one for ESX.

The correct client API package is called "VMware Server Windows client package" and can be downloaded at the download page of VMware Server: http://download3.vmware.com/software/vmserver/VMware-server-win32-client-1.0.1-29996.zip


first of all: very nice work. very nice. working great in my testing area here. just one little questen (is may be answered anywhere)

is it possible NOT to compress the vmwares? or even greater: decide in the ini file which vm to compress and which not?

is it possible NOT to compress the vmwares? or even
greater: decide in the ini file which vm to compress
and which not?

Yes, with the next version (or my alternate version until the 'official' one is released - see previous posts).

Use 'MakeZippedFile=False' for each section of the ini that you do not want to zip. This will cause the copied files to NOT be deleted (as they normally would after a sucessful zip)

Chris.

I've hacked the backup script down to a minimal version and reworded some bits to give a shutdown script. The idea is to use the same ini file but call vm-shutdown.vbs instead of vm-backup.vbs. (From a UPS etc).

Can someone tell me if this is redundant. When shutting down a vmware host server ('baremetal'?) do the vm's get a chance to shutdown gracefully, or do they suffer a virtual power failure?

If anyone wants to look at the script: www.ourplace.org.nz/vmscript/VM-Shutdown.zip

Cheers,
Chris

btw - what about adding support for lzop compression? (binary for windows
available at http://www.lzop.org/)

did anybody give it a try (e.g. compressing some large imagefile) ?
you should really compare compression speed of lzop against zip or gz compression - i tell you, you will be impressed!

I was willing to give it a look, but just installing it seems to involve more effort than I am interested in putting into it. :(

p.s. Debugging is a real bear.
The next version should be ready later today.

I was willing to give it a look, but just installing it seems
to involve more effort than I am interested in putting into it. :(

huh?
did you miss the link for the binary download ?
it`s at http://www.lzop.org/download/lzop101w.zip

p.s. Debugging is a real bear.
even worse. ;)

uncle Brian Kernighan telling words of wisdom for this:

"Debugging is two times harder than writing programs. So, if you write your programms as clever as you can, then, by definition, you are not smart enough to debug your programs! "

The next version should be ready later today.
great to hear!

I've hacked the backup script down to a minimal
version and reworded some bits to give a shutdown
script. The idea is to use the same ini file but call
vm-shutdown.vbs instead of vm-backup.vbs. (From a UPS
etc).

While it was not done for this purpose it will be possible to configure the options on the new version to shutdown a machine. There are two new variables (both false by default) SuppressCopy and SkipRestartVM. I added these to help speed up the testing process (the script runs in seconds without these two operations, especially if the VM is already off) but they will be left in the code. Setting both these options to true effectively just shuts down the VM.

Well, it took longer than expected but it's finally done:

2/25/07 - V3.5

* All the messages have now been moved to their own INI file. This is a completely
separate INI file than the variables use. Unlike the variables, messages MUST be
defined in the INI file as there are no defaults in the script itself. A default
messages INI file has been provided. Please feel free to change or translate it.
* Renamed variable: INIFilename to VariablesINIFileName
* Added new variable
* MessageINIFilename - This is the name of the file containing the messages. It
must be defined in the script itself.

* A running log file is now created while the script runs. The log file notes all
the steps as they occur. The text of the log messages are also defined in the
messages INI file so you can easilly change or translate it. Note: I really wish
I had done this sooner becasue the data generated by the log is extremely helpful
in troubleshooting.
* Added new variables
* CreateLogfile - Default is true. Should a log file be created.
* MaskPassInLogs - Default is true. Should passwords be shown in the log files
* AttachLogFile - Default is true. Attach logs to email messages
* CleanUpLogFiles - Default is false. Clean up old log files
* NumberLogsToKeep - default is 30. How many old log files to keep, per VM
* Unlike other messages Log messages can only be one line long but they can still
Use variable names.
* The log file is created in a logs subfolder. If you are zipping then the log will
have the same name as the zip file with a .log extension. If you are not zipping
then it will have a name like vmidentifier-date/time.log

* Added everything contributed by PCost_CL in their posting. In some cases I
expanded on it and/or made some adjustments, but all the basics are there.
* Added Cint casting to all imported INI integer variables. (this should fix some
(problems with comparison operations not working correctly)
* Modified code to allow simple copying of files and not require them to be zipped
as well.
* Added variables
* DefaultCopyPath - Default is D:\backups\, Location where files will be copied to
* MakeZippedFile - Default is true. Should the copied files be zipped
* KeepCopyFiles - Default is false. Don't delete copied files (after being zipped)
* Bypass all zip code if MakeZippedFile is false
* Made the copy and zip operations/variables more distinct and separate.
* Added new error message
* CopyPathNotFoundErrorMessage
* Changed drive space check to check that space exists for the copyfile location
not the backupfile location.

* There were numerous internal changes involving the order of operations, timing,
syntax, and changes to subroutines to accomidate the new features described above.
If you have never tried modifying the code this won't matter one bit to you.

* Added a drive space check for the backupfile location. However this is something that
is only logged since we dont know the space needed for the zip file.

* Added code to detect and terminate an endless loop caused by improperly formatted
variables in message lines.

* Added new variables
* RestartVMEvenIfOff - Default is false. Start VM even if it was originally off
* SuppressCopy - Default is false. setting it to true will prevent the script from
copying files. It's for testing purposes (speed things up) but I'm leaving it in.
* SkipRestartVM - Default is false. Setting it to true will prevent the script from
starting the VM. It's for testing purposes (speed things up) but I'm leaving it in.

* Changed default PauseBeforeCompress value from 1 to 0

* Changed the text of VariablesErrorMessage

* Renamed message CriticalVMShutdownErrorMessage to VMShutdownCriticalErrorMessage due
to a name conflict with another message.

NOTE: If upgrading, DefaultCopyPath will need to be set in ini file (probably to match
DefaultBackupPath).

http://www.fileden.com/files/2007/1/16/650957/VMBackup.zip


First of all: Great work! Realy great work. Im testing it here with my test-farm and it is working great. and of course the option for not cpmpressing the files is amazing :) Make my farm much more flexible.

Just one question: Did the VM power off or shutdown? It looks like they will be powered off and not shutdown. This could be a problem with database or ADS servers.

Sounds great. . .will try to put it into testing soon. One challenge I am trying to figure out is how to skip some drives.

A few of our servers have a second disk that is just pure data. . .I don't really want to "image" those every time I do a backup. . .

Any ideas on how to accomplish that?

Ok, I just tried to set up the new script. . .for some reason sending mail isn't working anymore. . .

Ok, I just tried to set up the new script. . .for
some reason sending mail isn't working anymore. . .

Any Antivirus Software n that maschine? Something like McAffee? This could block the mail sent. Just open an dosbox und try to telnet your mail server (telnet yourmailserver 25) and check if your mail server allows relaying.

Yes, there is AV, but telnetting to port 25 works fine. . .the mail server logs don't even show attempts to connect. . .?


Just one question: Did the VM power off or shutdown?
It looks like they will be powered off and not
shutdown. This could be a problem with database or
ADS servers.

It shuts down gracefully. Heck, if you have the VM configured to run a script on shutdown they will even run.

TechFan,

Do you have the script configured to make a log. Is log created? Does the script run and just no email?

Yes, log is created, but no email. . .log doesn't say anything about trying to send. . .only about setting email parameters.

Can you post or pm your log file.

log sent via PM

Yes, log is created, but no email. . .log doesn't say
anything about trying to send. . .only about setting
email parameters.

Email is not (currently) sent in interactive mode.

I did find an design flaw in that interactive mode does not read in any variables from the INI file. I'm adding an INTERACTIVE section to the INI that will be used when in interactive mode. You will be able to specify the various values, including mail settings, that you want to use when in interactive mode there. If you specify a vmfile or zipfile then that will be the default but you will be able to change it at run time.

02/27/07 - V3.51

* Changed interactive mode to now read in a new section, INTERACTIVE, from the
INI file. Previously interactive mode was not reading in variables for the
INI file. All the variables can be defined in this section. If you supply the
VMfile or Zipfile there then this will be the default when you are prompted for
these values.
* Added New Variable:
* MailInInteractive - Default is false. Send mail in interactve mode
* Changed Log Messages:
* ZeroArguementsNoVM=No Virtual Machine path specified (either in the INI file
or by the user)
* ZeroArguementsNoZipName=No Zip filename was specified (either in the INI file
or by the user)
* Added new Log Messages:
* ZeroArguements2=Using the INTERACTIVE section from the ini file
* ZeroArguementsUserVM=User Supplied the VM path, %\^VMFile^%
* ZeroArguementsUserZipFile=User Supplied the Zipfile name, %\^ZipFile^%
* SetupMailSystemNoThanks=Mail is disabled for interactive mode per
configuration options
* When in interactive mode you are no longer prompted for the zipfilename if
MakeZippedFile is false
* Email can now be sent when in interactive mode if MailInInteractive is
true.

http://www.fileden.com/files/2007/1/16/650957/VMBackup.zip

Sent PM. I will try using this one, but I had the variables defined in the actual script, so it shouldn't have been a problem of undefined variables.

.. but I had the
variables defined in the actual script, so it
shouldn't have been a problem of undefined variables.

Yeah, that one had me for a bit when i was checking your log file.

In any case V3.5 would not send mail in interactive mode becuase it assumed it didn't have valid mail settings. Without valid mail settings the script would get a long delay while the mail system timed out. I wanted to get rid of the delay so i disabled mail in interactive mode. For whatever reason the solution implemented in V3.51 didn't come to me earlier.

Hm, okay. . .still no mail, need to check mail server logs more though. Is there a way to document in the log that the message was sent (result of send mail command)?

Also, it does not seem that the Interactive section of the INI file are over-riding those set in the script. . .can I just remove the setting in the script and run them all from the INI file?

Ok, hacked a fix it seems. Our mail server doesn't allow the mail to come from random sendors, it has to be a valid user. . .so put that in static and I got the message! :-)

Ok, I was hoping that I could get the email to have the VMName in the subject, but setting the default subject didn't work because VMName isn't known at that point. So, either default subject needs to be set later. . .not sure how to best do that so it can still be set from the settings section. I see the two places I would need to hack the script (success and error) or would need to add another line to reset the default later in the script. Is this info available earlier and I just don't recognize how to get it?

Ok, I was hoping that I could get the email to have
the VMName in the subject,

What do you consider to be the VMName? Are you talking about the name listed under Inventory in the VMware Server Console?

Ok, hacked a fix it seems. Our mail server doesn't
allow the mail to come from random sendors, it has to
be a valid user. . .so put that in static and I got
the message! :-)

That would do it :)

What do you consider to be the VMName? Are you
talking about the name listed under Inventory in the
VMware Server Console?

Hm, yes, that is what I was thinking. . .

It seems we should also use some sort of variable to set the send from addresses. . .


It seems we should also use some sort of variable to
set the send from addresses. . .

Not my cup of tea, but its easy enough - already done in the next verson (don't know when that will be available since I'm in progress on some other much more involved changes that are not done yet).

As for the VM name (listed under Inventory in the VMware Server Console) - The script does not currently read this information. I don't even know if the API can get that info (but I'd imagine that it can). What's currently used to identify the VM is the name of the folder where the files are located. In the script this is called the VMIdentifier. You would be able to put that in the subject as it is known at the time.

Sounds good. Will modify the subject to use that variable and just use the manual hack for the from address for now.

Actually, doesn't look like that info is known either when the ini values are set at the top?

Hey guys, I have a question about the operation of your script..

How do you script multiple vms at once? Do I have to create a batchwith multiple sections of the ini or can I put multiple vmfile attributes into one section?

I remember the earlier versions would simply backup everything underneath a certain folder, say "C:\virtual machines\" It doesn't look like this works anymore as you have to specify a path to the vmx file?

I remember the earlier versions would simply backup
everything underneath a certain folder, say
"C:\virtual machines\" It doesn't look like this
works anymore as you have to specify a path to the
vmx file?

When i originally looked at Saxa's script didn't appear that it did this, but I could certainly be wrong. When you specify the vmx file the script gets the folder that that file is in and copies everything in that folder. I think this is essentially the way it's always been done.

The script only makes a connection to the VM using API's and shuts down before copying then starts up after copying. It only does this for one VM.

You would only want to put info for one VM in each INI file section.

I would imagine that a batch file would work fine to run on multiple VM's. I use scheduled tasks and have a single task for each of the VM I want to backup.

Actually, doesn't look like that info is known either
when the ini values are set at the top?

It's known at that time. Looking at it again I see what the issue is. DefaultMailSubject is a variable and variables are not pumped through the sub that evaluates text strings for variable names , only message lines are.

It will probably be best to edit the code in the script as you discovered earlier.

As far as we know there's no way to get this to work on 64 bit systems either, right?

See the discussion between Louch and Saxa on page 4.

Yeah, it's odd, I'm having a different problem. It says it can't find messages.ini ..... which is very, very odd since it's sitting in the same folder.

odd, I specified the full path in the script and it seems like it's working now.

I'm wondering if there would be some way to set the zipping process to low priority? It tends to slow down the virtual machines when the compression step is taking place.

odd, I specified the full path in the script and it
seems like it's working now.

Perhaps that just one of the quirks with running on 64bit?

Maybe, it would be REALLY nice if it could enumerate all the vm's registered on the server and back them all up automatically though.

The list of registered VM's can be found in the registry in the following key:
HKEY_LOCAL_MACHINE\SOFTWARE\VMware, Inc.\VMware Server\AccountInfo

it can also be done using the vmware-cmd CLU

Just read the 7zip's manual: there are some switches you can use to set the priority of zipping.

Maybe, it would be REALLY nice if it could enumerate
all the vm's registered on the server and back them
all up automatically though.

It looks to be possible but I think it would be rather difficult to do that in a way that's flexible enough to meet the needs of the most people.

Just read the 7zip's manual: there are some switches
you can use to set the priority of zipping.

I must admit, that was my first thought too. I briefly looked through the help file and didn't see any options that looked to do what was asked, perhaps I missed it.

Possibly copying and zipping to another physical disk (not the one the VM uses) in the machine would help.

I briefly looked through the help file and didn't see any options that looked to do what was asked, perhaps I missed it.

There were some priority options, I know it. Will take a look at it tomorrow.

Possibly copying and zipping to another physical disk (not the one the VM uses) in the machine would help.

Anyway!

Yes, there indeed are some. Found a mention of some in their forum:
http://sourceforge.net/forum/message.php?msg_id=4122354

You can also start 7zip with the windows "start" command and put it in lower priority that way as well. . .

hi saxa,

thanks for you excelent script. But one question I have:

you defined values for cm.username and cp.password. Is there a way to omit this values and use the credentials of the user who is running the script?
background: the script will be run from BackupExec and this is running as a service with a special domain account. And I don't want to put the password in clear text in this command-file.

thanks in advance

Hello pbuechel,

you defined values for cm.username and cp.password. Is there a way to omit this values and use the credentials of the user who is running the script?

Many of us would like to know how to use at least the encrypted passwords in the script, but I don't know the way...

hey guys,

im running version 3 and im happy with it so far (havent changed them to version 3.5 since everything is working and far too many servers to go to and change the scripts... will get around to it)

BUT I am having one issue... for some reason it will not delete the OLD zip files it makes....

I have set it in the ini file to allow delete and even set a minimum file size but it still doesnt delete it...

here is what i have in the ini file:

CleanUpBackupFiles=TRUE
NumberBackupsToKeep=1
MinFileSize=1

am i missing somthing?

ok so i upgrade to version 3.51 and it does now delete the files...

thx for the updated version!

Hi,

i´ve tested the script and it is working well. Thank you.

But i have a VM with started Programs after login.
Now the VM is going down, backup and started.
The VM wait at the login screen.
The Programms wait to start - It´s not a service application!

Is there any possibility to suspend the VM in place of
shut down them, and after supend the Machine doing a backup ?

Greetings
Paul

Hi,

i´ve tested the script and it is working well. Thank
you.

But i have a VM with started Programs after login.
Now the VM is going down, backup and started.
The VM wait at the login screen.
The Programs wait to start - It´s not a service
application!

Is there any possibility to suspend the VM in place
of
shut down them, and after supend the Machine doing a
backup ?

Greetings
Paul


This topic keeps coming up and was covered earlier. See the following links for the reasoning:

(second post):
http://www.vmware.com/community/thread.jspa?messageID=407181

Also see the second post by KevinG here:
http://www.vmware.com/community/thread.jspa?messageID=434750

That being said I did start modifying the script to support suspending of the VM's. If I recall everything is done except for the code to actually suspend. I stopped there because I was not sure how to do it (I suspected it's really no different than shutting down) and I did not want to mock up something to do all the testing.

I'll take a look at it and perhaps i can post what's done and someone else can either make the changes themselves, or i can give it a try if someone wants to be the guinea pig and test it.


Just set the Guest VM to autoadminlogon=1 and put your application in the startup folder. Volia! there you go!

You could also set a scheduled task on the guest VM to shut the application gracefully before the backup started on the host.

I'm getting a defaultcopypath cannot be found error. the paths are fine as they work perfectly from the console. no idea why the script can't find them.. any ideas?

edit,, nevermind. I Had a space between the '=' and the path... :/

Message was edited by:
faulty

I still don't see what the big deal of suspending VM's first is. . .how many times am I going to restore it to another VM server? Not often. And if I do, deleting the suspend files will be just fine.

I haven't had time to implement it yet though.

And if I do, deleting the suspend files will be just fine.

keep in mind, that this is more or less equivalent to just hitting the power button or pulling the plug of a machine.
you may loose data and leave your filesystem or application (database,whatever...) in inconsistent state

Sure, that doesn't mean I plan to do it. . .just like you don't plan to do a hard reset but sometimes you have to do it. Windows is very good at recovering. And of course, I would be running this backup during the night when no users are connected to the database. . .so the chances of doing it damage are very very low.

Thanks for posting this. I will have to find time to work with it but it shows a lot of promise.

Hi,

thank you very much for that awesome vbs!!!!!

It works perfectly fine, even in a W2k3 R2 x64 enviroment with minimal modification.

Here a short summary of what has to be changed for x64:

1. the script must run with:

%windir%\SysWOW64\cscript vm-backup.vbs [configssectionininifile]

2. to avoid the error that 7-zip (x64 Version) ist not correctly found in the registry, the vm-backup.vbs must be changed as follows.

find the line:
Seven_zip_reg = wshShell.RegRead("HKLM\SOFTWARE\7-Zip\Path")

and replace it with:
Seven_zip_reg = wshShell.RegRead("HKLM\\SOFTWARE\\7-Zip
Path")

Well here it is. With the exception of the code to actually suspend the VM (and some of the error/log messages) I've been running this version for a few months now so I can safely say that if you do not enable suspending it's stable. If you do enable suspending - I don't know. I think the code is correct, but I have not tested it myself

Other than the suspend option there only one or two minor fixes and additions.

04/30/07 - V3.6

NOTe: The code to actually suspend the VM's is 100% untested!!! Everything else has been tested and appears to work fine.
The default settings will not enable the backing up suspended VM's and thus does not execute the untested code.

If you want to use the suspend option be sure to read the warning below.


'***WARNING***WARNING***WARNING***WARNING***WARNING***WARNING***WARNING***WARNING***WARNING***WARNING***WARNING***WARNING***
'
' Restoring a suspended VM to a different host machine may not work!!!
'
'***WARNING***WARNING***WARNING***WARNING***WARNING***WARNING***WARNING***WARNING***WARNING***WARNING***WARNING***WARNING***


* Added code to support suspended VM's and suspending VM's instead of shutting them down
You can choose to support only VM's already suspended, or you can go all in and
suspend the VM's instead of shutting them down too.
* Added new variables:
* AllowSuspend - Default is false. Set to true to backup a VM in the suspended state
* SuspendNotShutdown - Default is false. Set to true to suspend the VM instead
of shutting it down. Note that AllowSuspend must be true if you want to back it up
* RestartVMEvenIfsuspended - Default is false. Start the VM even if it was
originally suspended
* Added new log messages:
* VMOrigStateSuspended=The VM is currently suspended.
* ShutdownVMIsSuspended=No need to shutdown the VM as it's already suspended
* StartupVMOrigSuspended=The startup operation for the VM will be skipped because
the VM was originally suspended
* StartupVMYes=The VM will now be restarted
* SuspendVMStart=Attempting to suspend the VM
* SuspendVMEnd=VM successfully suspended
* SuspendVMNotSuspended=the VM was sent a suspend command but it did not suspend
* SuspendVMHung=It appears that the VM is hung, now attempting a hard suspend
* SuspendVMHardHung=Hard suspend was unsuccessfull. Please check the VM
* SuspendVMFailed=The VM could not be suspended but it does not appear to be hung
* Added new error messages
* VMSuspendHardErrorMessage1=The VMware Backup Script determined that the virtual machine '%\^VMIdentifier^%' was hung
for more than %\^VMStopHungSeconds^% seconds and performed a hard suspend.__
* VMSuspendHardErrorMessage1=This shutdown was successfull but you may want to look into why the machine hung.
* VMSuspendHardErrorMessage1=
* VMSuspendHardErrorMessage1=Backup processing will continue and you should expect another message.
* VMSuspendCriticalErrorMessage1=The VMware Backup Script attempted a hard suspend on the virtual machine '%\^VMIdentifier^%'.__
* VMSuspendCriticalErrorMessage2=This suspend attempt failed. Please check it's state ASAP.
* VMSuspendErrorMessage1=The VMware Backup Script couldn't suspend the virtual machine '%\^VMIdentifier^%' in a reasonable time.__
* VMSuspendErrorMessage2=The machine did not appear to be hung though. Please check it's state.
* Renamed log messages:
* VMStateOn to VMOrigStateOn
* VMStateOff to VMOrigStateOff
* VMStateError to VMOrigStateError
* Changed Log messages:
* StartupVMSkip=The startup operation for the VM will be skipped per the
configuration options
* StartupVMOrigDown=The VM will not be restarted as it was originally shutdown
* There was some minor internal reorganization to accomidate this change. If you
have never tried modifying the code this won't matter one bit to you.

* Reworked the code that generates the log messages.

* Added the log file to the zip or copy location

* Added ability to hard code the From address for emails
* Added new variable:
* MailFrom - Default is null. If this is null then the from address on email is
built by the script and is in the form "VM-" & VMIdentifier & "@" & MyMailDomain.
If you enter a value here then that will be the from address on email.

The newest version of the script is located here (older versions also included in the zip):
http://www.fileden.com/files/2007/1/16/650957/VMBackup.zip


Hi! Beeing just a joe user I have a problem to backup a VM from a second server (both servers running vm server 1.03). In the ini I use

[BES]
VMFile=D:\VM BES\BES\BES.vmx
CleanUpBackupFiles=true
remote_server=True
remote_host=192.168.0.1
remote_user=administrator
remote_pass=XXX
remote_share=\\Phlox\BES
PauseBeforeCompress=120

Where
VMFile=D:\VM BES\BES\BES.vmx
is the path to the vmx on the server to backup from (Phlox)
BES is the name of the share on Server Phlox

Unfortunately this does not work ... script says he can not find it ...

Share is working, admin has all rights to it

Thanks a lot!
Oliver


i'm getting a connectvmerror.

The VMware Backup Script couldn't connect to the virtual machine

I know the path's are correct, it only does it to machines that are turned off, any idea what the problem is.

This script is working fine on about 10 of my servers but for some reason I can not get it to work on two of my servers.

The one server I keep getting the following error:

The request to halt this virtual machine failed because the corresponding VMware Tools script did not run successfully. If you have configured a custom halt script in this virtual machine, please inspect it for errors; otherwise, please submit a support request.

The script can be deactivated on the Power page of the virtual machine settings by unchecking "Before powering off" in the Run VMware Tools Scripts section.
I uninstalled VMWARE tools and reinstalled it but still get the message. I have no other scripts running on the server...

has anyone come across this? if so any fix? This leaves my server in an almost shutdown phase so i have to restart it in the morning

The second error i get is the script will not shutdown one of my servers:

The VMware Backup Script couldn't shut down the virtual machine 'HIST-HAS' in a reasonable time. The machine did not appear to be hung though. Please check it's state.

The server does not shutdown nor does it hang... but the backup does not complete which isnt good for me :(

any suggestions on the above to issues would be great.

thx in advance!


Anyone have a linux version of this? For a Linux host

This script is working fine on about 10 of my servers
but for some reason I can not get it to work on two
of my servers.

The one server I keep getting the following error:

The request to halt this virtual machine failed
because the corresponding VMware Tools script did not
run successfully. If you have configured a custom
halt script in this virtual machine, please inspect
it for errors; otherwise, please submit a support
request.

he script can be deactivated on the Power page of the
virtual machine settings by unchecking "Before
powering off" in the Run VMware Tools Scripts
section.

I uninstalled VMWARE tools and reinstalled it but
still get the message. I have no other scripts
running on the server...

has anyone come across this? if so any fix? This
leaves my server in an almost shutdown phase so i
have to restart it in the morning

The second error i get is the script will not
shutdown one of my servers:

The VMware Backup Script couldn't shut down the
virtual machine 'HIST-HAS' in a reasonable time. The
machine did not appear to be hung though. Please
check it's state.

The server does not shutdown nor does it hang... but
the backup does not complete which isnt good for me
:(

any suggestions on the above to issues would be
great.

thx in advance!


The problem are the guests you trying to backup, as you can see from the script's output. The guests can't be shutdown.

What are the guest OSes on that ones? Have you checked their states, as the script said?

BTW: if your guests are WinNT 4 ones, they will be never shut down. It means, you can't use our script to backup them...

Anyone have a linux version of this? For a Linux host

Sure. The script you see in this thread can handle a linux host being started on a Windows workstation.

If you are looking for the Linux-only version, keep in mind, that you can't run any VBScripts on Linux box.

But, there are some Linux-only scripts which run on bash. Here is the one I have "programmed":

code
#!/bin/bash

# Give me a name such as vm-backup or any other you like :)

# We need 2 arguments

if [ $# != 2 ]; then
echo ""
echo "Shell script for backing up of virtual machines."
echo "Usage: $(basename $0) /path/to/config/file.vmx /path/to/backup/file.tgz"
echo "Spaces in path and in file names are not supported."
echo ""
echo "List of the registered virtual machines follows."
echo ""
vmware-cmd -l
echo ""
exit
fi

# Get the info if the VM is running. If true, it must be powered on after completion.

if [ "$(vmware-cmd -q "$1" getstate)" == "on" ]; then

if [ "$(vmware-cmd -q "$1" getheartbeat)" == "0" ]; then

# VMware Tools not found
echo ""
echo "The VMware Tools is not installed inside the guest \"$1\"."
echo "Please shut down it manually and run the script again."
echo ""
exit

else

WAS_ON=true
vmware-cmd $1 stop soft

fi

elif [ "$(vmware-cmd -q "$1" getstate)" == "off" ]; then

# VM is off
WAS_ON=false
else

# The state couldn't be determined
echo ""
echo "Please check the state of the guest \"$1\"."
echo "Maybe your activity is needed, such as creating of the new SID."
echo ""
exit

fi

sleep 10

# Ready for copying

VM_DIR=$(dirname "$1")

BK_DIR=$(dirname "$2")

cp -r $VM_DIR $BK_DIR

sleep 10

# Start the VM if it was running

if [ $WAS_ON == true ]; then
vmware-cmd $1 start
sleep 180
fi

# Create a tarball and cleanup

WHAT_TO_COMPRESS=$BK_DIR/$(basename $VM_DIR)

tar cfvz $2 $WHAT_TO_COMPRESS
sleep 10
rm -r $WHAT_TO_COMPRESS

# Calculate the size

size=$(du -h $2)
size=${size//$2/""}

echo "The virtual machine \"$1\" was compressed to \"$2\". File size: $size"
exit

[/code]


MY host machines are both W2K3 machines.

The first server never goes down and stays running.

the second server is almost at a shutdown state and once i click ok on the message, it shutsdown...

so not really sure what to do :|

---------------------------------

on another note, in order for this script to backup a linux machine that is running on a windows host, does the linux machine need vmware tools? im assuming it does... if so i guess i need to learn how to install vmware tools on debian and red hat :|


Has anyone seen this script or can someone please help me make or create this script???

All my host servers are running sometype of windows 2003 server and a script like this would work wonders....

(copied and pasted this script from here: http://www.vmware.com/community/message.jspa?messageID=637490#637490)

I have the same problem and my solution is:

* Reboot the virtual server with vmware-cmd start

The downtime will be about 2 minutes

* Delete the shadow copy with vshadow (if you do not want to save it)

OK, the downtime is about 2 minutes, but I am willing to do that to be able to backup the whole virtual machine an be able to reboot the virtual server on an other host in no time in case of disaster ... and its free...

Jens


i would like to shutdown the vmware machine, take a snapshot, turn back on the vmware machine, than copy the snapshot to a usb drive and maybe delete the snapshot and zip the copy after it is done???
if i was sometype of programmer i would do this but i know nothing of programming....

can someone pls help me out here!

thx in advance


Guys, I have created a VM automation program that can be used to automate almost anything including backing up VMs.

Right now, I use it to create Norton Ghost backups of my virtual machines.
For my current needs, I do partition-to-image backups, but other backup types are available too.

It works flawless and is faster than the Zip method.
The program was created in Java and can be scheduled to run.

For backups, you can backup in sequence an unlimited number of VMs.

Nothing needs to be installed in the VMs to be backed up.
All you need are:
1. a utility VM, which we will call the Automation VM
2. a ghost.exe or ghost32.exe file for Ghost backups

This is better than Ghostcast since:
1. You only need the cheapest licensed version of Norton Ghost (you only need a ghost.exe or ghost32.exe file)
2. No network usage unless you are creating the images to network share

Guys, I have created a VM automation program that can be used to automate almost anything including backing up VMs.

Could you publish it?

I thought about something similar, too: using VBScript.

how long is the vmware off for? and how long does the entire process take?

can someone take a look at what i posted about vss if possible :|

thx


Indeed, it would be great if this script could do shadow copies. . .seems like downtime would be much shorter. . .

yes a script that will down the server, take a shadow copy (which takes 30 seconds) bring back up the server and than copy the shadow copy directory to a usb drive or a nas would be great since downtime will only be like 2 minutes...

some of the vmware servers that are running in my environment can only be down for 5-10 mins tops and a backup solution like this one would work wonders!

I found this link that someone has created a script that works with windows virtual server that suspends the server takes a shadow copy and than unsuspends the server and brings it back up and copies the shadow copy somewhere else.... maybe this can help some programmers on how it might work with vmware (instead of suspending vmware, downing it but the rest of the process kind of the same?)

http://cwashington.netreach.net/depo/view.asp?Index=1049

Sorry, was an error...

Message was edited by:
saxa

Guys, I have created a VM automation program that
can be used to automate almost anything including
backing up VMs.

Could you publish it?

I thought about something similar, too: using
VBScript.


The problem I am having right now is that the program contains another API I have developed that don't want to share.

I need to explore more on Java obfuscation.
One part of the code would be open source and the rest would be restricted.

Again, the core aspect of all this is the VM Automation Framework (now known as VAF :) ).
VAF works anywhere Java and VMware are supported.
What you do during the framework's callbacks is really up to you.
This way, people can implement backups or other tasks as they please.

For instance, while it is acceptable to backup suspended VMs for some, for others it is not.
It is also problematic to attempt a Ghost backup of a suspended VM.
The intent of the framework is to allow you to do whatever works for you.
VAF processes profiles and does not care what those profiles stand for.

My Ghost backup process is an example of what you can do.
At scheduled times, per profile, Ghost partition images of the VMs are harvested to a given storage location without me having to do anything.

Life on easy street. :)

I'm trying to use the latest script to shut down a VMWare Server session, then copy the image to another server - not necessarily for backup, but for failover.

I have the remote server stuff configured, but I keep getting "ERROR: There was an error connecting to the server."

Just to verify - I should be pointing at the host server, correct? (I've tried both).

Port 902 is open. The authentication should be fine.

What the heck am I missing?
Thanks

Hello,

to be honest:
I have not read the whole thread :-)
But I tried to run the V3.6 on a W2k3 64 bit operating system with vmware Server v1.0.2 , that results with the efollowing error:

2007-06-04T13:40:29 Found Messages INI file
2007-06-04T13:40:29 Started reading contents of Messages INI file
2007-06-04T13:40:29 Finished reading contents of Messages INI file
2007-06-04T13:40:29 Creating VMCom objects
2007-06-04T13:40:29 **ERROR**: Error encountered creating VMCom objects

Will the script not work in this enviroment?

Regards,
Markus

Markus,

I have not read the whole thread

No problem. But you should read the comment in the script itself. Because there is no VMCom library for 64bit you must run the script in a 32bit context.

Use the following command line:

code%WinDir%\SysWOW\WScript.exe vm-backup.vbs[/code]

or create a cmd file with such contents.

Regards
Alex

Hi,

thanks for your help.
After I installed the 32bit Version of 7zip and used the command:
WinDir%\SysWOW64\WScript.exe c:\batch\vm-backup.vbs

the script ran ok.

Regards,
Markus

Need a little help!
Got the latest script and everything seems to run fine except that not all the files out of my VM directory are copied. The copy process takes less than a minute and copies a few logs and then continues on as if it completed copying. It reports 20+gig of space needed for copy but just doesn't do it. I've tried it on multiple VM machines with the same result.
It's got to be something I'm doing.

Any ideas?

hello,

at first i have to say thank you for this great script! but i have a little problem using it for machines on remote locations. my configuration works fine if the vm host copies the machine to the backup location (a network share).

but if i try to copy the machine calling the script from the backup server, i receive the following error:

2007-07-24T15:40:42 Added remote server settings: Host:**.**.**.**, User:**********, Pass:********, Port:902
2007-07-24T15:40:42 Attempting to make a connection to the server
2007-07-24T15:40:43 Server connection successfull
2007-07-24T15:40:43 Attempting to make a connection to the virtual machine \\SHARE\MACHINE.vmx
2007-07-24T15:40:57 **ERROR**: There was an error connecting to the virtual machine \\SHARE\MACHINE.vmx

(i've changed the paths in the config, of course =)

on both machines vmware server is fully installed and access rights seem to be ok.

connection to server is ok, but there are some restrictions connecting the virtual machine... (i've tried it with the domain admin user, too)

has anybody an idea/hint to solve this problem?

thanks in advance!

ps: vmware server is version 1.0.3 - script version is 3.6

Message was edited by:
j.hero

2007-07-24T15:40:43 Attempting to make a connection to the virtual machine \\SHARE\MACHINE.vmx

Is OK that the script fails. The path is not correct. The path to the vmx file must be the one from the host, not from the client running the script.

The correct path could be something like

codeC:\Virtual Machines\My Really Advanced Guest\MACHINE.vmx[/code]

(i've changed the paths in the config, of course =)

I'm still getting mails from the users of the very first script's version: before I published it, I've forgotten to change my real values to "default" ones :)

I'm still getting mails from the users of the very
first script's version: before I published it, I've
forgotten to change my real values to "default" ones
:)

Now THATS funny!

I am enjoying the 3.6 version of the script. I am using it as an interim solution to developing a full executable.

I am making a few changes to it and will share when I am complete:

1) Can feed and array of VM Names cscript/wscript VMBackup.vbs "server1,server2,server3,etc" to have the script iterate through and backup all VMs with one scheduled task.

2) I have managed to get some code working that will take a remote volume shadow copy using WMI (Windows Management Interface). I can go to the shadow copy manually, but have not figured out how to use WMI to connect (remotely) to the shadow copy to get the files from there. I am still working on it. If anyone else has some insight, please let me know, I will continue to work on it as often as I can.

3) I am using RoboCopy, but that is really not much of a script change, but I can add a conditional check like there is for 7zip.

4) Biggest change and most time consuming. I am breaking all the activities in main into distinct Subroutines and Functions. This will make it easier for other contributors to understand the code and plug in new functionality.

I will try to maintain backwards compatability with all existing options. I do travel quite a bit on business so time is not something I have a lot of, but I do feed a need to contribute. Reorganizing the code gave me a real appreciation of the work you guys have already put into it.

I am beginning testing on the new version with organized Subroutines and Procedures and, once I am finished testing, will send it to???

Does anyone have any interest in putting this on SourceForge (I have never started a SourceForge project so I do not know if it is free or not) where we can keep track on versions and all update in one place. It may encourage more contributions.

Thanks for all your hard work.

I am having the same problem. Was wondering if got a solution yet?

Thanks

hi,

this script look good..

the VM Server host should be running Windows 2003 Server Standard.

can i run on a VM Server guest running Windows NT 4 Server?

how can i have the best way to backup a Windows NT 4 Server guest?

please help and thank you.

hi to all,

thanks for all the work. did anybody actually really solve the problem of making a consistent online-backup (not shutting down the vm´s), for example using vss (volume shadow copy service) ???

about downtime:
i am running three winxpx64 host systems with 8GB of RAM and 2-4 vms on vmware server 1.03 (since my company is cheap, they do not want to buy an extra win2k3 server for the host or vmware esx for each host). the vm´s have up to 80GB disks in 2GB splits.

i would like to make once a day a full image backup for each host.
with that kind of data the vm´s would be offline for hours.

any suggestions?

thx
afficionado

I haven't finished the shadow copy stuff yet. Since my last post, I have been booked on 3 projects. The XSL programming project I am working on it taking a lot of my time right now. I am hoping to finish it this week or next and should have more time to work on it. I was hoping someone might figure out how to connect to a remote shadow copy after doing the snapshot. That is all I have left to figure out. I am able to remotely take a shadow copy, I can then manually connect to it, but cannot figure out the WMI calls to programatically connect. If anyone has any ideas or can research this, we can put our info together and get it done. Otherwise, I will work diligently as possible once my billable project status settles down a bit.

When I posted I was working hard and heavy on this stuff. Unfortunately my time bookings change quickly so I apologize for not getting this done quickly.

i have try the script and seem that it cannot shutdown the NT 4 Server, it has a prompt to power off manually.

how can i solve the issue?

i wish to have a backup for the NT 4 Server guest. how can i do it the best way..

please help and thank you.

i have try the script and seem that it cannot shutdown the NT 4 Server, it has a prompt to power off manually.

AFAIK: no way. WinNT doesn't support ACPI, that's why it can be shut down from within the guest, but the guest doesn't know how to disable the power on itself...

I'm not sure I'm right... ;)

so please help...

any solution...or customise...

i remember that when i installed nt4 workstations years ago that i replaced their hal with some different one which could do power-off at shutdown.

here`s some information:
To enable poweroff in Windows NT, you will need a hal.dll that is capable of shutting down
your workstation. You can try one that's supplied with service pack 4 (or higher): hal.dll.softex
Just extract the service pack (with the /x option),

There are several machine-specific HAL.DLL's, and you MUST extract the matching HAL*.DLL.SOFTEX
from the service pack. To avoid problems when someone overwrites the good HAL.DLL with a bad
one it's better to rename HAL*.DLL.SOFTEX to %SystemRoot%\System32\HALPOWER.DLL for instance,
copy the line in %SystemDrive%\BOOT.INI which loads the current system, alter the description
and append " /HAL=HALPOWER.DLL". Now one can choose between the two HALs and has a fallback if
the new one fails.

If you like NT to automatically poweroff at shutdown, set the following registry key to 1:
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\PowerdownAfterShutdown

Sorry to drag up an old post, but what if I did not want the zip files created? How can I disable it without killing the script?
Thanks in advance
Dallas

can the VB script run on Win XP machine install VMWare Server?

can the VB script run on Win XP machine install VMWare Server?

Why not try it yourself? ;)

Yes, it will run. Don't forget to install 7zip.

Sorry to drag up an old post, but what if I did not
want the zip files created? How can I disable it
without killing the script?
Thanks in advance

Dallas, I thought, i made a good job regarding documentation... SirShagg made even more...

Just find the strings which are responsible for:

- deleting the copied folder

and delete them / comment them out.

i use the ver 3.6 script and do not seem to run.

what should i have in the .ini file...

any example for below

directory = d:\virtual machine\winnt
backup folder = d:\backup
keep 3 copy
7zip enable

also can the script support vss for w2k3 server?

There is actually an option for this so no code editing is necessary.

MakeZippedFile = True

Set to false in your INI file.


i use the ver 3.6 script and do not seem to run.

what should i have in the .ini file...

any example for below

directory = d:\virtual machine\winnt
backup folder = d:\backup
keep 3 copy
7zip enable

Seriously, read the comments in the code and look at the default vm-backup.ini file that comes with it. Theres example in there.


after either using the modified hal.dll or ppntapm.sys

if select Shut Down from NT4, the compueter will power down the computer.

if using the backup script.. it still prompt "it is now safe to turn off your computer"

solution 2
First, extract the file ppntapm.sys from the latest service pack (6a) by executing "sp6i386.exe /X". This will extract all files to a directory of your choice. Then copy ppntapm.sys to your %systemroot%\system32\drivers directory.

Next, make a reg file with the following content, and name it ppntapm.reg:

<pre>REGEDIT4

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\ppntapm]
"Group"="Power Management"
"Start"=dword:00000000
"Error Control"=dword:00000001
"Tag"=dword:000000a1
"Type"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\ppntapm\Parameters]
"UseDefaultSegmentLimits"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon]
"PowerdownAfterShutdown"="1"</pre>

That's it. Now your compueter will power down the computer when you select Shut Down from NT4.

i have use a shutdown program to shutdown the server within the guest.

the vmware-cmd guest stop does not able to power off NT 4 Server.

so after the guest is shutdown. i look thru the script and still not able to run... when run

it say error "this is not a valid ini file"

VM-Backup.ini
[BAAN]
DefaultBackupPath=d:\backups\
VMFile=D:\Virtual Machines\BAAN\BAAN.vmx
CleanUpBackupFiles=TRUE
NumberBackupsToKeep=2
MinFileSize=1
ReportToMail=xxxxx@xxxx.com
MyMailDomain=xxxx.com
SMTPServer=xxx.com
SMTPPort=25
DefaultMailSubject=VMWAre backup
[INTERACTIVE]

can someone help. thank you.


I'm not sure if this has already been addressed, i apologize if it has, but I'm running servers and I can't afford the "downtime". Is there a way to "suspend" or "pause" the VM's?
It doesn't seem like our best bet to be restarting these servers every night.

I'm running servers and I can't afford the "downtime".

Here on the Server forum, we all run servers :)

Well, there is a way to suspend your VMs to backup them. But, the time difference between "suspend" and "shutdown" is in equal the time which the guest OS needs to be correctly shut down (one minute) and to start (also one minute).

Think about it: shut down means downtime. Suspend means downtime, too.

Is there a way to "suspend" or "pause" the VM's?

Sure. But I would really suggest you: never suspend any production machine if you want to keep your correct data. Let me describe, why.

Do you know something like suspending in the real server world? No? Me too. And your servers don't know this as well.

Now, imagine, your server software works with transactions. Nowadays, it does every server OS and every server application, such as MSSQL, Exchange, Oracle, MySQL...

Let's say, we run some DB on a (real) server, which computes a bigger transaction right now. And it looses the power. What will the DB software do after you brought the server back? It will see the not committed transaction and will roll back it. So, the data is consistent.

And now let's play this game on a virtualized server. It accomplishes our transaction, and in the middle of it, our backup script / software / user suspends the machine. After restoring, the DB software will think: "Hey, I had a crash, but my transaction runs further. No way!" and will produce a rollback. And it means, your transaction is either deleted without logging (best case) or is executed until the suspending. I have also seen that the same transaction was accomplished twice...

Check out my adaptation of this script, which minimizes downtime to ~1min! http://communities.vmware.com/thread/109563

Guten Tag,

ich bin am 5.11.2007 wieder im Haus.

Bei wichtigen Problemen wenden Sie sich bitte an Herrn Herbert Bachmann oder Herrn Dr. Matthias Weger.

Ihre E-Mail wurde nicht weitergeleitet

Danke
Stefan Holzwarth


Just wanted to say thanks a lot for this very cool script.

Is doing what I need, easy to understand due to good comments in the vbs, even me is able to undnerstand what is happening where and what to change to fit personal environement, and most important : worked at first run.

Great work :-))


I've been using this script, but i'm having trouble with a new VM I created that has two drives. It is backing up vmdk of the Windows drive, but not the data drive vmdk. Any ideas?


too bad the script does not work in Win NT 4 vmware guest.


saxa,

I am having an issue with cleanup in your script. If I use the 7Zip switch -v4g, when the script goes to delete old backup files, it deletes all of the "parts" of the split zip.

For example:
Win2k3.zip.001
Win2k3.zip.002
Win2k3.zip.003
Win2k3.zip.004

If I have set Keep Backups to 1, then all but Win2k3.zip.001 is deleted.

Any ideas on how to fix that in the script?

Thanks.

This document was generated from the following thread: Advanced VB script for backup of VMs on Windows hosts
Average User Rating
(0 ratings)




There are no comments on this document