Monthly Archives: September 2014

Creating a clone from a snapshot on Vmware vSphere

There are times when you need something from a snapshot of a VM, but might not want to rollback to the snapshot to get it. This could be because the VM is in production and you cannot interrupt it, or you are extremely risk averse, or various other reasons.

The work around, is to create a clone of the snapshot. This will allow the existing VM to run uninterrupted, while a new clone is created.

I use the following Powershell/PowerCLI code to do that, and then disable the virtual NIC. After all, you don’t want the clone VM coming up with the same name and IP as your production VM, that would defeat the purpose of doing the clone in the first place. Just note that it doesn’t really have any troubleshooting or error catching.

$vmname = "myserver"
$VMCluster = "Production Cluster"
$VMResourcePool = "Pre-Production"
$VMdatastore = "VMFS-DATA-1"
$SnapshotNum = 0

$vm = get-vm -name $vmname | get-view
$clonename = "Clone_" + $vm.name
$clonefolder = $vm.parent

$cloneSpec = new-object Vmware.Vim.VirtualMachineCloneSpec

$cloneSpec.Location = new-object Vmware.Vim.VirtualmachinerelocateSpec
$CloneSpec.Location.Pool = (get-cluster $VMCluster | get-resourcepool $VMResourcePool | get-view).MoRef
$CloneSpec.Location.Host = (get-vm -name $vmname | get-vmhost | get-view).MoRef
$CloneSpec.Location.Datastore = (get-datastore -name $VMdatastore | get-view).MoRef
$cloneSpec.Snapshot = $vm.Snapshot.RootSnapshotList[$SnapshotNum].snapshot

$cloneSpec.Location.DiskMoveType = [Vmware.Vim.VirtualMachineRelocateDiskMoveOptions]::moveAllDiskBackingsAndDisallowSharing

write-host ("Creating clone - " + $clonename)
$vm.CloneVM_Task($cloneFolder, $cloneName, $cloneSpec)
Do {
$task = (get-task | where {$_.Name -eq "CloneVM_Task" -and $_.State -eq "Running"})
If ($task -ne $null) {Write-host ("Waiting for clone to complete - " + $task.percentcomplete[0] +"%")}
Start-sleep -s 5
}
While ($task -ne $null)
$VMadapter = get-vm -name $Clonename | get-networkadapter | set-networkadapter -startconnected:$false -confirm:$false
Write-host $VMadapter + "disabled."

Most of the information for putting this together was taken from here:
http://www.vmdev.info/?p=202

Advertisements

Leave a comment

Filed under Microsoft, Powershell, VMware