Hi guys,
A while back Mr. LucD helped me with a script that automatically deletes any VM that has been powered off longer than 14 days. The script does work as intended but I wanted to see if someone could help me by modifying it so that instead of me having to update the script manually to exclude a VM from being deleted, we could simply make it so that if a virtual machine or multiple virtual machines are inside a folder, these would not get deleted. In other words, if we manually move a VM to a folder, the script will NOT remove any of the virtual machines inside it.
Below is the script I am using.
##Load all VMware related snap-ins
#Add-PSSnapin VMware.VimAutomation.Core
Get-Module -ListAvailable VM* | Import-Module
##vCenter connection information
$vcenter = 'vcenter instances'
$vcenteruser = 'vadmin'
$vcenterpw = ''
##Connects to all vCenter instances
Connect-VIServer $vcenter -User $vcenteruser -Password $vcenterpw
#Here's where you can exclude any virtual machines from being removed by the script. You will need to un-comment this line.
#You will also need to comment the $excludedVM = @{} line in order to honor this line.
#$excludedVM = 'Some VM' -----> This is where a folder would be a lot safer to use.
#Here's where you can ignore the exclusions. If you un-comment this line, all virtual machines that meet the 7 day criteria will be removed.
#If you comment this line, then you will need to un-comment the #$excludedVM = 'VM Name Line' in order to honor this line.
$excludedVM = @{}
#Here you're defining the any VM variable
$vms = @{}
#This piece will get all powered off VMs and exclude the ones from the list that were defined in the $excludedVM variable
Get-VM | where {$_.PowerState -eq "PoweredOff" -and $excludedVM -notcontains $_.Name} | % {$vms.Add($_.Name, $_)}
#Get-VM | where {$_.PowerState -eq "PoweredOff"} | % {$vms.Add($_.Name, $_)}
#Exclude any virtual machine that was powered off before the last 7 days
Get-VIEvent -Start (Get-Date).AddDays(-7) -Entity $vms.Values -MaxSamples ([int]::MaxValue) | where {$_ -is [VMware.Vim.VmPoweredOffEvent]} | Sort-Object -Property CreatedTime -Unique | % {$vms.Remove($_.VM.Name)}
#Remove the remaining VMs
#Remove-VM -VM $vms.Values -DeletePermanently -Confirm:$false -WhatIf
Remove-VM -VM $vms.Values -DeletePermanently -Confirm:$false