This is a fairly simple script but I thought I’d share. I needed to delete a group of about 6 virtual machines this morning. I could easily do this through the vSphere GUI but I figured I’d write a quick script so I could use it for future deletions.
$VMs = (Get-Content servers.txt) foreach($vm in $VMs){ $active = Get-VM $vm if($active.PowerState -eq "PoweredOn"){ Stop-VM -VM $vm -Confirm:$false Start-Sleep -Seconds 10 Remove-VM -VM $vm -DeleteFromDisk -Confirm:$false -RunAsync} else {Remove-VM -VM $vm -DeleteFromDisk -Confirm:$false -RunAsync} }
Updated Script:
$VMs = (Get-Content servers.txt) $vmObj = Get-vm $vms foreach($active in $vmObj){ if($active.PowerState -eq "PoweredOn"){ Stop-VM -VM $active -Confirm:$false -RunAsync | Out-Null} } Start-Sleep -Seconds 7 foreach($delete in $vmObj){ Remove-VM -VM $delete -DeleteFromDisk -Confirm:$false -RunAsync | Out-Null}
This script will run a lot quicker and the code is a bit cleaner.
Isn’t supposed to be Remove-VM VM -DeletePermanently instead of Remove-VM -VM $delete -DeleteFromDisk
Thanks works great!!!
Thanks Brian! Although, It worked for me running $VMs = (Get-Vm testvm* )
as I needed to get a list of hosts with the name testvm – of course this is example and you change it to suit your needs.
Hello Brian,
I’m looking for a script which will power-off, unregister virtual machines and remove from inventory without deleting them from the disk
Do you have similar script?