Hi guys,
In my labs I often have to provision a lot of “trashable” VMs and I wanted to run a single command to remove them easily.
From this idea I wrote a small script :
clear $ExpectedPowerStatus = "PoweredOff" $VMName = read-host 'Type the name of the VM to delete. If more than one VM are expected, use the wildcard "*"' write-host $VMName -ForegroundColor Yellow function getVMPowerStatus() { param([parameter(mandatory=$true)]$vm) write-host "Function getVMPowerStatus:Getting Power state for VM $vm" -ForegroundColor DarkYellow$VMstate = (get-vm $vm).PowerState write-host "> Power state of $vm : is $VMstate" if($VMState -ne $ExpectedPowerStatus) { return $false } } function PowerOffVM() { param([parameter(mandatory=$true)]$vm) write-host "Function PowerOffVM:Terminating VM $vm" -ForegroundColor DarkYellow try { stop-vm $vm -confirm:$false -ErrorAction stop write-host "> turned off successfully" -ForegroundColor Greenreturn $true } catch { write-host "> Failed to turn off VM" -ForegroundColor Red } } function DeleteVM() { param([parameter(mandatory=$true)]$vm) write-host "Function DeleteVM:Preparing to delete VM $vm" -ForegroundColor DarkYellow $IsPoweredOff=getVMPowerStatus($vm) if($IsPoweredOff -ne $True) { PowerOffVM $vm } try { get-vm -Name $vm | Remove-VM -DeletePermanently -confirm:$false -ErrorAction stop write-host "> VM deleted successfully" -ForegroundColor Green }catch { write-host "> VM deletion failed" -ForegroundColor Red } } function Main() { $VMtoDelete = @(get-vm $VMName) foreach($vm in $VMtoDelete){DeleteVM -vm $vm} } Main
From your powercli console, if not already done, connect to your vCenter/ESX and run the script