Searching for way’s to create easy backup’s of a few virtual machines, i came on the website gestalt it (http://gestaltit.com/all/tech/virtualization/simon/vmware-backup-powercli-script/).
On this website there is a script which will create a snapshot of a VM, then clone it (thin provisioned) and finally remove the snapshot off the original VM.
Backup Script
# Import Backup CSV
$backupinfo = Import-Csv C:\scripts\mybackups.csv
#Set Date format for clone names
$date = Get-Date -Format "yyyyMMdd"
#Set Date format for emails
$time = (Get-Date -f "HH:MM")
#Connect to vCenter
Connect-VIServer ""
foreach ($customer in $backupinfo)
{
$vm = Get-VM $customer.MasterVM
#Send Start Email
C:\scripts\backupstartedemail.ps1
# Create new snapshot for clone
$cloneSnap = $vm | New-Snapshot -Name "Clone Snapshot"
# Get managed object view
$vmView = $vm | Get-View
# Get folder managed object reference
$cloneFolder = $vmView.parent
# Build clone specification
$cloneSpec = new-object Vmware.Vim.VirtualMachineCloneSpec
$cloneSpec.Snapshot = $vmView.Snapshot.CurrentSnapshot
# Make linked disk specification
$cloneSpec.Location = new-object Vmware.Vim.VirtualMachineRelocateSpec
$cloneSpec.Location.Datastore = (Get-Datastore -Name $customer.BackupDS | Get-View).MoRef
$cloneSpec.Location.Transform = [Vmware.Vim.VirtualMachineRelocateTransformation]::sparse
$cloneName = "$vm-$date"
# Create clone
$vmView.CloneVM( $cloneFolder, $cloneName, $cloneSpec )
# Write newly created VM to stdout as confirmation
Get-VM $cloneName
# Remove Snapshot created for clone
Get-Snapshot -VM (Get-VM -Name $customer.MasterVM) -Name $cloneSnap | Remove-Snapshot -confirm:$False
#Send Complete Email
C:\scripts\backupcompletedemail.ps1
}
#Disconnect from vCentre
Disconnect-VIServer -Confirm:$false
Send Started Email Script
#Set Date format for emails
$timestart = (Get-Date -f "HH:MM")
$emailFrom = ""
$emailTo = ""
$subject = "[$vm - Backup Started]"
$body = "Backup Details
-------------
VM Name:",$vm,"
Clone Name:","$vm-$date","
Target Datastore:", $customer.BackupDS,"
Time Started:", $timestart
$smtpServer = ""
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom,$emailTo,$subject,$body)
Send Completed Email Script
#Set Date format for emails
$timecomplete = (Get-Date -f "HH:MM")
$emailFrom = ""
$emailTo = ""
$subject = "[$vm - Backup Complete]"
$body = "Backup Details
-------------
VM Name:",$vm,"
Clone Name:","$vm-$date","
Target Datastore:", $customer.BackupDS,"
Time Started:", $timestart,"
Time Completed:", $timecomplete
$smtpServer = ""
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom,$emailTo,$subject,$body)
CSV File
The content of the csv file is very simple. This is what mine looks like:
MasterVM,BackupDS
VM1,BackupDataStore
VM2,BackupDataStore
Pingback: PowerCLI: VMware Backup Script | Mes postits