VMware Cloud Community
LucD
Leadership
Leadership

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

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

}


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

Reply
0 Kudos
4 Replies
BBarbee
Contributor
Contributor

Thank you...

Reply
0 Kudos
BBarbee
Contributor
Contributor

Lucd,

Sorry this is a late reply...

I used the sample you supplied but i then get the following.

Get-VM : Cannot validate argument on parameter 'Name'. The argument is null or empty. Provide an argument that is not

null or empty, and then try the command again.

At C:\Users\b.barbee\Documents\Scripts\lucd3.ps1:24 char:23

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

+                       ~~~~~~~~~~

    + CategoryInfo          : InvalidData: (:) [Get-VM], ParameterBindingValidationException

    + FullyQualifiedErrorId : ParameterArgumentValidationError,VMware.VimAutomation.ViCore.Cmdlets.Commands.GetVM

here is the modified .ps1 file

What i modified is to re read the directory and delete all the vm's that are now powered off.

Thanks again for your help

Reply
0 Kudos
LucD
Leadership
Leadership

Try changing this line

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

into this

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


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

BBarbee
Contributor
Contributor

That worked....

Thank you so much...

Reply
0 Kudos