Hi guys,
A little while ago Luc was kind enough to provide a script that would remove any virtual machine that has been powered off longer than 14 days. So far the code works as expected. What I need help with now is to basically be able to exclude a VM from this list in case we need to keep it longer. In other words, even if the VM meets the criteria of 14 days, it can be excluded from being removed by the script. Below is the code that Luc provided. Thanks!
$vms = @{}
Get-VM | where {$_.PowerState -eq "PoweredOff"} | % {$vms.Add($_.Name, $_)}
Get-VIEvent -Start (Get-Date).AddDays(-14) -Entity $vms.Values -MaxSamples ([int]::MaxValue) |where {$_ -is [VMware.Vim.VmPoweredOffEvent]} |
Sort-Object -Property CreatedTime -Unique | % {
$vms.Remove($_.VM.Name)
}
Remove-VM -VM $vms.Values -DeletePermanently -Confirm:$false -WhatIf
$sMail = @{
From = 'virtualadmin@company.com'
To = 'vadmin@company.com'
SmtpServer = 'smtprelay.company.com'
Subject = "Removed $($vms.Keys.Count) VM powered off more than 14 days"
Body = ($vms.Keys | Out-String)
}
Send-MailMessage @sMail