2 Replies Latest reply on Jul 16, 2018 12:30 PM by LucD Branched to a new discussion.

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

    BBarbee Lurker


      I have been looking at various posts for the last week or so and havent found exactly what I am looking for.


      I plan on kicking off powershell jobs with Jenkins that will go to a specific folder in vSphere, find all VMs older than 5 days, power off the ones that are on, then delete them.


      We have a testing group that has a habit of using jenkins to spin up vm's for testing builds, but then does not delete them.


      I have found parts of code that look right  but i can't make it all come together.


      Apologies to anyone this code came from...I copied a lot from various web sites and forums.


      Here is the piece that will find VMs powered on in the time specifed


      $Folder = get-folder powershell | get-vm

      $vmOn = $Folder | where {$_.PowerState -eq "PoweredOn"}

      $On = Get-VIEvent -Entity $vmOn -Start (Get-Date).AddDays(-700) -Finish (Get-Date).AddDays(-5) -MaxSamples ([int]::MaxValue) | where {$_ -is [VMware.Vim.VmPoweredOnEvent]} |

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

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

        New-Object PSObject -Property @{

          VM = $_.Group[0].Vm.Name

          "Last Poweron"= $lastPON

          Duration = [math]::Round((New-TimeSpan -Start $lastPON | Select -ExpandProperty TotalDays))




      this does show me VMs that were powered on prior to 5 days ago...but when I try to do a "Stop-VM $On" it is not finding the VM name, but another part of the FullyFormatedMessage.

      Duration Last Poweroff         VM

      -------- -------------         --

             0 5/29/2018 10:51:56 AM bb-003-new

             0 5/29/2018 10:51:56 AM bb-tf-demo-3

             0 5/29/2018 10:51:55 AM bb-new-000

             0 5/29/2018 10:51:56 AM BB-001


      I would not be opposed to looking at it from a "Created Time" so anything created longer than 5 days ago would get turned off and then removed.

      I have played with that as well and had the same issues.


      CreatedTime          VM

      -----------          --

      5/22/2018 9:50:12 AM bb-003-new

      1/4/2018 3:22:01 PM  bb-tf-demo-3

      5/17/2018 11:05:1... BB-002

      5/22/2018 9:52:23 AM bb-new-000

      5/17/2018 11:04:4... BB-001




      Any help would be appreciated.

      Thanks in advance