Script to remove VMs that have been off more than 30 days
August 14th, 2014
My users developed a habit to keep their un-used VMs for too long and it slowly eat up our storage. I need a way to enforce our 30 days retention policy. A bit of searching and I end up with this script. Oh and it sends emails too.
1 2 3 4 5 6 7 8 9 10 11 |
$vms = Get-VM | where {$_.PowerState -eq "PoweredOff"} $vmPoweredOff = $vms | %{$_.Name} $events = Get-VIEvent -Start (Get-Date).AddDays(-30) -Entity $vms | where{$_.FullFormattedMessage -like "*is powered off"} $lastMonthVM = $events | %{$_.Vm.Name} $moreThan1Month = $vmPoweredOff | where {!($lastMonthVM -contains $_)} $moreThan1Month | Remove-VM -DeletePermanently -Confirm:$false $vmNames = $moreThan1Month | Select -ExpandProperty Name Send-MailMessage -From report@domain.com -To me@domain.com -SmtpServer mail@domain.com ` -Subject "Removed $($moreThan1Month.Count) VM" -Body ($vmNames | Out-String) |
Categories: Data Center, Virtualization