Automation

 View Only
  • 1.  Exclude VMs from being removed by automated script.

    Posted Nov 13, 2018 05:02 PM

    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



  • 2.  RE: Exclude VMs from being removed by automated script.

    Posted Nov 13, 2018 05:14 PM

    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



  • 3.  RE: Exclude VMs from being removed by automated script.
    Best Answer

    Posted Nov 13, 2018 06:08 PM

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



  • 4.  RE: Exclude VMs from being removed by automated script.

    Posted Nov 13, 2018 06:22 PM

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