Linked Clone Script Extracts and Examples

From vWiki
Jump to navigation Jump to search

Create Linked Clone

The following will allow you to create a Linked Clone of an existing VM. Similar to normal cloning the source VM doesn't need to be powered off, but if possible is probably a good idea.

Be aware that Linked Clones cannot be Storage vMotioned (they can be cold migrated)

$SrcVmName = "Master-VM"               # Name of VM to clone (will be base/parent of linked clone

$NewVmName = "Child-VM"                # New of new linked clone
$CreateInFolder = "Spawn"              # Optional - folder for new linked clone


$Vm = Get-VM $SrcVmName

# Create temporary snapshot to create clone from
$SrcVmSnap = New-Snapshot -VM $Vm -Name "Clone Snapshot" -Quiesce:$true -Confirm:$false

# Get view of source VM
$SrcVMview = Get-View (Get-VM $SrcVmName)

# Create RelocationSpecification - defines destination of clone
$relocateSpec = New-Object Vmware.Vim.VirtualMachineRelocateSpec
$relocateSpec.DiskMoveType = [Vmware.Vim.VirtualMachineRelocateDiskMoveOptions]::createNewChildDiskBacking
  
# Create CloneSpecification - defines overall cloning operation
$cloneSpec = New-Object Vmware.Vim.VirtualMachineCloneSpec
$cloneSpec.Location = $relocateSpec
$cloneSpec.Snapshot = $SrcVmSnap.Id

if ($CreateInFolder) {
    $Folder = (Get-Folder $CreateInFolder).Id
} else {
    $Folder = $Vm.Parent
}

$SrcVMview.CloneVM($Folder, $NewVmName, $cloneSpec)

Remove-Snapshot $SrcVmSnap -Confirm:$false

Whilst you can specify that the new VM is created on a different datastore to the parent VM, only the VMDK(s) are located there, all other VM files are located on the source datastore. Therefore its normally preferable to move following the new following its creation using Move-VM, but this isn't required add the the destination datastore to the Relocation Specification...

$relocateSpec.Datastore = (Get-Datastore "DatastoreName").Id