Scheduled Task in VSphere – using PowerCLI to delete existing machines
Let me preface this post with the fact that I have just got my hands on the new Vsphere 4.1 release from VMware. However, on just a high level look at the scheduled tasks in 4.1, if you want to use a scheduled task to clone a machine, let’s say for a “poor man’s backup” if you do not have another backup device or some type of software, if when the scheduled task runs and sees the “backup” machine already existing, it will bomb out with the error that the machine already exists.ย I still do not see the option to delete the existing VM if it exists.
There is a way using the VMware PowerCLI and Powershell to get around this. Again, let me preface this as probably not the best way to be backing up your virtual machines, but if you do not have a better way to do this, you can use another stand alone ESX box or another cluster perhaps to swap virtual machines back and forth between them, cloning on a regular basis.
Download the VMware PowerCLI:
https://communities.vmware.com
- Install the PowerCLI on a workstation or your Vsphere box itself
- Create a user on your local VSphere box or a domain account that you want to use to clone your workstations
- In a PS1 file you can place the following command to be run by the VMware powershell module:
For example, this can be placed in a file on the root of C called deletevms.ps1
Connect-VIServer vsphere1.somedomain.com -User yourVIuserhere -Password viuserpassword
Get-VM VM1_backup | Remove-VM -DeleteFromDisk -Confirm:$false
Start-Sleep -Seconds 10
Get-VM VM2_backup | Remove-VM -DeleteFromDisk -Confirm:$false
Start-Sleep -Seconds 10
Get-VM VM3_backup | Remove-VM -DeleteFromDisk -Confirm:$false
Start-Sleep -Seconds 10
Get-VM VM4_backup | Remove-VM -DeleteFromDisk -Confirm:$false
Start-Sleep -Seconds 10
In a batch file which can also reside on the root of C or another directory of your choosing, place the following syntax:
Windows 2008 R2 Vsphere box:
powershell -PSconsolefile “C:Program Files (x86)VMwareInfrastructurevSphere PowerCLIvim.psc1” -command c:deletevm.ps1
Windows 2003 -32 bit box with Powershell 1.0 installed (note in VSphere 4.1, you cannot use a 32 bit box, so this would be VSphere 4.0 and under running on a 32 bit box):
C:WINDOWSsystem32windowspowershellv1.0powershell.exe -PSconsolefile “C:Program FilesVMwareInfrastructurevSphere PowerCLIvim.psc1” -command c:deletevm.ps1
After you have your batch file, simply created a schedule task to run your batch file before your VSphere scheduled task runs.ย This will make sure your backup machine is blasted before the new copy of the machine comes down.