Friday, August 10, 2012

Delete VM then Clone VM Powershell script

I recently found myself in a situation where I needed to create an automated taks that would create a clone of a VM on a weekly basis.

Now I know there are tools and software out there that can take full VM backup and I run vRanger on the majority of my VMs, but this was a special case senerio.

So below is a script that will first check to see if there is already a snapshot of my vm, if so it deletes it, then it will make a new clone. If there are any errors in the process it will email me.

$date = Get-Date
$vcServer = "vcenter.you.com"
$fromVMname = "SourceVM"
$newVMName = "CloneVM"
$tgtEsxName = "ESXi.you.com"
$tgtDatastoreName = "Datastore1"
$userName = "account"
$passWord = "password"
$notes = ("Clone of: " + $fromVMname + " for backup. Created on: " + $date)

# Connect to the vCenter Server

Connect-VIServer -Server $vcServer -User $username -Password $passWord




#
# Test to see if $newVMname already exists in vCenter Server and 
# set $vmExist to a value other than $null if it does
$vmExist = Get-VM -Name $newVMname -ErrorAction SilentlyContinue


#
# Delete the VM $newVMname if $vmExist returns a value other than $null
if ($vmExist -ne $null)
{
 Remove-VM -deletefromdisk -VM $newVMName -confirm:$false
}
#
# Create a clone of $fromVMname to $newVMName, email if there is an error
$cloneTask = New-VM -Name $newVMName -VM (Get-VM $fromVMname) -VMHost (Get-VMHost $tgtEsxName) -Datastore (Get-Datastore $tgtDatastoreName) -RunAsync
Wait-Task -Task $cloneTask -ErrorAction SilentlyContinue
Get-Task | where {$_.Id -eq $cloneTask.Id} | %{
     if($_.State -eq "Error"){
          $event = Get-VIEvent -Start $_.FinishTime | where {$_.DestName -eq $newVMName} | select -First 1
          $emailFrom = VDIPowerCLI@you.com
          $emailTo = me@you.com
          $subject = "Clone of " + $newVMName + " failed"
          $body = $event.FullFormattedMessage
          $smtpServer = smtp.you.com
          $smtp = new-object Net.Mail.SmtpClient($smtpServer)
          $smtp.Send($emailFrom, $emailTo, $subject, $body)
     }
}
#
# Set the notes field of the VM $notes
Set-VM -VM $newVMName -Notes $notes -confirm:$false
#
#Disconnect from the vCenter Server
Disconnect-VIServer -Server $vcServer -Confirm:$false 


With the script created I setup a Windows Scheduled task on my vCenter server to run this script once a week.

So far it has been working well.

No comments:

Post a Comment