VMware Cloud Community
mars0077
Enthusiast
Enthusiast
Jump to solution

Exclude VMs from being removed by automated script.

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

0 Kudos
1 Solution

Accepted Solutions
mars0077
Enthusiast
Enthusiast
Jump to solution

Sir!! Thank you very much. I will test it out and will let you know.

View solution in original post

0 Kudos
3 Replies
LucD
Leadership
Leadership
Jump to solution

Try like this

$excludedVM = 'vm1','vm2','vm3'

$vms = @{}

# Get all powered off VMs, excluding the ones from the list in $excludedVM

Get-VM | where {$_.PowerState -eq "PoweredOff" -and $excludedVM -notcontains $_.Name} | % {$vms.Add($_.Name, $_)}

# Exclude the ones that were powered off in the last 14 days

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 the remaining VMs

Remove-VM -VM $vms.Values -DeletePermanently -Confirm:$false -WhatIf

# Send email

$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


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
mars0077
Enthusiast
Enthusiast
Jump to solution

Sir!! Thank you very much. I will test it out and will let you know.

0 Kudos
mars0077
Enthusiast
Enthusiast
Jump to solution

Mr. Luc! As always, thank you very much sir. All worked as expected.

0 Kudos