Tag Archives: clone-vm

Clone Virtual Machine in VMware with PowerCLI

Cloning a virtual machine can either be performed when powered on or off. I personally prefer to create a clone whilst the VM is offline to ensure that all data is in a consistent state.

Turning a VM off during the business day might not go down to well with your customers/users.

The following can be saved as a ps1 script and scheduled to run out of hrs in a maintenance window. If you specify the email setting in the script an email will be generated once completed to notify that the change has been completed.

Prerequisite:

Install VMware vSphere PowerCLI, script has been tested with version 6 R1 available hereĀ vSphere PowerCLI 6.0 Release 1

All the variables are declared at the start of the script and prefixed with the dollar $ symbol.

##Task Clone VM
##Declare variables
$VM2change = "test-server"
$VMclone = "$VM2change_clone"
$Hostesxi = "esxihost1.vsphere.local"
$vcenter_server ="vcenter.vsphere.local"
$vcenter_user ="administrator@vsphere.local"
$vcenter_pwd ="Password123"
##Email Settings
$emailServer = "192.168.1.1"
$sender = "powercli@vsphere.local"
$recipients = "admin@vsphere.local"
$dateofclone = $(get-date -f dd-MM-yyyy)
##Load VMware PS plugin
Add-PSSnapin VMware.VimAutomation.Core
##Connect to vCenter
connect-viserver -server $vcenter_server -User $vcenter_user -Password $vcenter_pwd
###########################Start- Custom Task #########################
##Stop VM
GET-VM -Name $VM2change| Stop-VMGuest -Confirm:$False
start-sleep -s 180
##Clone VM, set disk type to thin and create in template folder
New-VM -VM $VM2change -Name $VMclone -VMHost $Hostesxi -DiskStorageFormat Thin -Location "VM Template" -Notes "Clone created $dateofclone by David McIsaac"
##Convert to template
Set-VM -VM $VMclone -ToTemplate -Confirm:$False
##Start orignal VM
GET-VM -Name $VM2change| Start-VM -Confirm:$False
##Get Clone info
$VMcloneinfo = (Get-Template -Name $VMclone| fl *|Out-String)
##ping original VM
start-sleep -s 120
$isalive= (Test-Connection -ComputerName $VM2change -count 1|Out-String)
###########################End- Custom task #########################
##Compose email and send
$body = @" 
VM Clone Created,$VMcloneinfo.
Is original VM up??, $isalive
"@
send-mailmessage -from $sender -to $recipients -subject "VM Cloned $VM2change" -Bodyashtml "$body" -smtpserver $EmailServer
Advertisements