4 Replies Latest reply on Jul 16, 2018 10:26 AM by BBarbee Branched from an earlier discussion.

    Re: Want to sort VMs in a folder older than 5 days then delete

    LucD Guru
    User ModeratorsvExpertCommunity Warriors

      You are trying to stop the VM with an Event object, that doesn't work.

      Try like this

       

      # Get all powered on VMs in hash table

       

      $vmTab = @{}

      Get-Folder powershell | Get-VM | where {$_.PowerState -eq "PoweredOn"} | %{

         $vmTab.Add($_.Name,$_)

      }


      # Remove from the hash table the VM that were powered on in the last 5 days


      Get-VIEvent -Entity $vmTab.Values -Start (Get-Date).AddDays(-5) -MaxSamples ([int]::MaxValue) |

         where {$_ -is [VMware.Vim.VmPoweredOnEvent]} |

         Group-Object -Property {$_.Vm.Name} | %{

         $lastEvent = $_.Group | Sort-Object -Property CreatedTime -Descending | Select -First 1

         $vmTab.Remove($lastEvent.VM.Name)

        }


      # Stop & remove the VMs remaining in the hash table


      $vmTab.Values | %{

         $vm = Get-VM -Name $_.VM.Name

         Stop-VM -VM $vm -Confirm:$false

         Remove-VM -VM $vm -DeletePermanently -Confirm:$false

      }